<<< Back to Search

Snippet ::: File Flag Solution - Functions

Flags are useful to coordinate processes execution. From flag existance decisions in code can be made.

These three functions presented on this snipped allow to:

  • Create Flags
  • Test Flags
  • Delete Flags

with the flexibility of use an expiration option that will ignore file flags older than "Expiration seconds"

Core Snippet

# Snippet ::: File Flag Solution - Functions -_-
# PowerShellExamples.com

function New-Flag {
    <#
    .SYNOPSIS
        Create Flag
    .DESCRIPTION
        Create File flag only if not exist previously (or if is expired)
    .NOTES
        If flag exist previously report Warning
        If flag is expired create the new one (If expiration is active)

        To ignore expiration use 0

        Return result object
        Result.ExitCode: 0 Ok | 1 Warning | 2 Error
    .LINK
        https://powershellexamples.com/home/Article/25
    .EXAMPLE
        With Expiring flags

        New-Flag -flagPathFile "C:\Temp\MyFlag.txt" -expirationSeconds 2

    .EXAMPLE
        With no Expiring flags
        
        New-Flag -flagPathFile "C:\Temp\MyFlag.txt"
    #>
    
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        $flagPathFile,
        # Flag is consider expired on these seconds. Use 0 to ignore expiration
        $expirationSeconds = 0
    )

    $newFlagObj=[PSCustomObject]@{
        FlagPathFile = $flagPathFile
        ExitCode = $null
        ExitMessage = ""
    }
    
    # Report error if flag pre-exist
    if ((Test-Flag -flagPathFile $flagPathFile -expirationSeconds $expirationSeconds -deleteExpiredFlag).FlagExists) {
        $newFlagObj.ExitCode = 2
        $newFlagObj.ExitMessage += "Flag was already Exists"
    }else{
        # Creating Flag
        # Write result without returning anything to pipeline
        New-Item -Path $flagPathFile -ItemType File -Force -Confirm:$false | Out-String | Write-Verbose

        $newFlagObj.ExitCode = 0
        $newFlagObj.ExitMessage += "Ok"
    }

    return $newFlagObj
}

function Test-Flag {
    <#
    .SYNOPSIS
        Test if unexpired flag exist
    .DESCRIPTION
        Test if unexpired flag exist
    .NOTES
        If flag exist report 
        If flag is expired report not existance

        To ignore expiration use 0

        Return result object
        Result.ExitCode: 0 Ok | 1 Warning | 2 Error
    .LINK
        https://powershellexamples.com/home/Article/25
    .EXAMPLE
        $flagPathFile =  "C:\Temp\MyFlag.txt"
        if(Test-Flag -flagPathFile $flagPathFile -expirationSeconds 1 -deleteExpiredFlag -Verbose){
            Write-Host "Test #1: Flag is Present."
        }else{
            Write-Host "Test #1: Flag is not Present."
        }
    .EXAMPLE
        With Expiring flags asociating result to an object

        $testFlagObj = Test-Flag -flagPathFile "C:\Temp\MyFlag.txt" -expirationSeconds 2 -deleteExpiredFlag 
        if ($testFlagObj.FlagExists){
            Write-Host "-> Do action because Flag Exists"
        }else{
            Write-Host "-> Confirmed Flag NOT Exist."
        }

    .EXAMPLE
        With no Expiring flags
        
        if((Test-Flag -flagPathFile "C:\Temp\MyFlag.txt").FlagExists){
            Write-Host "-> Do action because Flag Exists"
        }else{
            Write-Host "-> Confirmed Flag NOT Exist."
        }

    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        $flagPathFile,
        [int]$expirationSeconds = 0,
        [switch]$deleteExpiredFlag
    )

    $testFlagObj=[PSCustomObject]@{
        FlagPathFile = $flagPathFile
        FlagExists = $null
        ExitCode = $null
        ExitMessage = ""
    }

    if (Test-Path $flagPathFile) {
        Write-Verbose "Flag detected: $flagPathFile"

        $testFlagObj.FlagExists = $true
        $testFlagObj.ExitCode = 0
        $testFlagObj.ExitMessage = ""

        if ($expirationSeconds -gt 0) {
            $flagobj = Get-Item -Path $flagPathFile

            $Time1 = $flagobj.LastWriteTime
            $Time2 = Get-Date
            $TimeDiff = New-TimeSpan $Time1 $Time2
            if ($TimeDiff.Seconds -gt $expirationSeconds) {
                
                $testFlagObj.FlagExists = $false
                $testFlagObj.ExitCode = 1
                $testFlagObj.ExitMessage = "Flag ignored because is older than $expirationSeconds seconds. "

                if ($deleteExpiredFlag.IsPresent) {
                    $testFlagObj.ExitMessage += "Flag Deleted."
                    remove-item $flagPathFile -Force -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
                }
            }
        }
    }
    else {
        $testFlagObj.FlagExists = $false
        $testFlagObj.ExitCode = 0
        $testFlagObj.ExitMessage = ""
    }

    return $testFlagObj
}

function Remove-Flag {
    <#
    .SYNOPSIS
        Remove flag
    .DESCRIPTION
        Remove flag
    .NOTES
        Return result object
        Result.ExitCode: 0 Ok | 1 Warning | 2 Error
    .LINK
        https://powershellexamples.com/home/Article/25
    .EXAMPLE
        Remove-Flag -flagPathFile "C:\Temp\MyFlag.txt"
    #>
    
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        $flagPathFile
    )

    $removeFlagObj=[PSCustomObject]@{
        FlagPathFile = $flagPathFile
        ExitCode = $null
        ExitMessage = ""
    }

    if (-not(Test-Path $FlagPathFile)) {
        $removeFlagObj.ExitCode = 1
        $removeFlagObj.ExitMessage = "Flag was already Deleted: $flagPathFile."
    }else{
        $removeFlagObj.ExitCode = 0
        $removeFlagObj.ExitMessage = "Ok"

        Write-Verbose "Removing Flag: $flagPathFile"
        # Write result without returning anything to pipeline
        Remove-Item -Path $flagPathFile -Force -Confirm:$false -ErrorAction SilentlyContinue | Out-String | Write-Host
    }

    return $removeFlagObj
}


# Usage (See practical examples and Comment-Help examples for more details)

# With Expiring flags
New-Flag -flagPathFile $flagPathFile -expirationSeconds 2

Test-Flag -flagPathFile $flagPathFile -expirationSeconds 2 -deleteExpiredFlag 

Remove-Flag -flagPathFile $flagPathFile | Out-String | Write-Host


# Without Expiration
New-Flag -flagPathFile $flagPathFile

Test-Flag -flagPathFile $flagPathFile

Remove-Flag -flagPathFile $flagPathFile | Out-String | Write-Host


Practical Sample

Copy text below into a power shell session and execute to see the code in action.


# File Management: File Flag Solution (Create/Test/Delete File Flags)
# This practical sample show File flag management including 
# - Create File Flag (New-Flag)
# - Test File Flag (with Expiration Option to ignore files older than "x" minutes)
# - Delete File Flag
function New-Flag {
    <#
    .SYNOPSIS
        Create Flag
    .DESCRIPTION
        Create File flag only if not exist previously (or if is expired)
    .NOTES
        If flag exist previously report Warning
        If flag is expired create the new one (If expiration is active)

        To ignore expiration use 0

        Return result object
        Result.ExitCode: 0 Ok | 1 Warning | 2 Error
    .LINK
        https://powershellexamples.com/home/Article/25
    .EXAMPLE
        With Expiring flags

        New-Flag -flagPathFile "C:\Temp\MyFlag.txt" -expirationSeconds 2

    .EXAMPLE
        With no Expiring flags
        
        New-Flag -flagPathFile "C:\Temp\MyFlag.txt"
    #>
    
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        $flagPathFile,
        # Flag is consider expired on these seconds. Use 0 to ignore expiration
        $expirationSeconds = 0
    )

    $newFlagObj=[PSCustomObject]@{
        FlagPathFile = $flagPathFile
        ExitCode = $null
        ExitMessage = ""
    }
    
    # Report error if flag pre-exist
    if ((Test-Flag -flagPathFile $flagPathFile -expirationSeconds $expirationSeconds -deleteExpiredFlag).FlagExists) {
        $newFlagObj.ExitCode = 2
        $newFlagObj.ExitMessage += "Flag was already Exists"
    }else{
        # Creating Flag
        # Write result without returning anything to pipeline
        New-Item -Path $flagPathFile -ItemType File -Force -Confirm:$false | Out-String | Write-Verbose

        $newFlagObj.ExitCode = 0
        $newFlagObj.ExitMessage += "Ok"
    }

    return $newFlagObj
}

function Test-Flag {
    <#
    .SYNOPSIS
        Test if unexpired flag exist
    .DESCRIPTION
        Test if unexpired flag exist
    .NOTES
        If flag exist report 
        If flag is expired report not existance

        To ignore expiration use 0

        Return result object
        Result.ExitCode: 0 Ok | 1 Warning | 2 Error
    .LINK
        https://powershellexamples.com/home/Article/25
    .EXAMPLE
        $flagPathFile =  "C:\Temp\MyFlag.txt"
        if(Test-Flag -flagPathFile $flagPathFile -expirationSeconds 1 -deleteExpiredFlag -Verbose){
            Write-Host "Test #1: Flag is Present."
        }else{
            Write-Host "Test #1: Flag is not Present."
        }
    .EXAMPLE
        With Expiring flags asociating result to an object

        $testFlagObj = Test-Flag -flagPathFile "C:\Temp\MyFlag.txt" -expirationSeconds 2 -deleteExpiredFlag 
        if ($testFlagObj.FlagExists){
            Write-Host "-> Do action because Flag Exists"
        }else{
            Write-Host "-> Confirmed Flag NOT Exist."
        }

    .EXAMPLE
        With no Expiring flags
        
        if((Test-Flag -flagPathFile "C:\Temp\MyFlag.txt").FlagExists){
            Write-Host "-> Do action because Flag Exists"
        }else{
            Write-Host "-> Confirmed Flag NOT Exist."
        }

    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        $flagPathFile,
        [int]$expirationSeconds = 0,
        [switch]$deleteExpiredFlag
    )

    $testFlagObj=[PSCustomObject]@{
        FlagPathFile = $flagPathFile
        FlagExists = $null
        ExitCode = $null
        ExitMessage = ""
    }

    if (Test-Path $flagPathFile) {
        Write-Verbose "Flag detected: $flagPathFile"

        $testFlagObj.FlagExists = $true
        $testFlagObj.ExitCode = 0
        $testFlagObj.ExitMessage = ""

        if ($expirationSeconds -gt 0) {
            $flagobj = Get-Item -Path $flagPathFile

            $Time1 = $flagobj.LastWriteTime
            $Time2 = Get-Date
            $TimeDiff = New-TimeSpan $Time1 $Time2
            if ($TimeDiff.Seconds -gt $expirationSeconds) {
                
                $testFlagObj.FlagExists = $false
                $testFlagObj.ExitCode = 1
                $testFlagObj.ExitMessage = "Flag ignored because is older than $expirationSeconds seconds. "

                if ($deleteExpiredFlag.IsPresent) {
                    $testFlagObj.ExitMessage += "Flag Deleted."
                    remove-item $flagPathFile -Force -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
                }
            }
        }
    }
    else {
        $testFlagObj.FlagExists = $false
        $testFlagObj.ExitCode = 0
        $testFlagObj.ExitMessage = ""
    }

    return $testFlagObj
}

function Remove-Flag {
    <#
    .SYNOPSIS
        Remove flag
    .DESCRIPTION
        Remove flag
    .NOTES
        Return result object
        Result.ExitCode: 0 Ok | 1 Warning | 2 Error
    .LINK
        https://powershellexamples.com/home/Article/25
    .EXAMPLE
        Remove-Flag -flagPathFile "C:\Temp\MyFlag.txt"
    #>
    
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        $flagPathFile
    )

    $removeFlagObj=[PSCustomObject]@{
        FlagPathFile = $flagPathFile
        ExitCode = $null
        ExitMessage = ""
    }

    if (-not(Test-Path $FlagPathFile)) {
        $removeFlagObj.ExitCode = 1
        $removeFlagObj.ExitMessage = "Flag was already Deleted: $flagPathFile."
    }else{
        $removeFlagObj.ExitCode = 0
        $removeFlagObj.ExitMessage = "Ok"

        Write-Verbose "Removing Flag: $flagPathFile"
        # Write result without returning anything to pipeline
        Remove-Item -Path $flagPathFile -Force -Confirm:$false -ErrorAction SilentlyContinue | Out-String | Write-Host
    }

    return $removeFlagObj
}




# Main Block
$flagPathFile =  "C:\Temp\MyFlag.txt"

Write-Host ">>> Tests with Expiring Flag" -ForegroundColor Magenta
Write-Host "`r`nNew flag - ignoring pre-existing flags expired in 2 seconds." -ForegroundColor Magenta
New-Flag -flagPathFile $flagPathFile -expirationSeconds 2 | Out-String | Write-Host

Write-Host "Test Flag before expiring - Asigning result to an object" -ForegroundColor Magenta
$testFlagObj = Test-Flag -flagPathFile $flagPathFile -expirationSeconds 2 -deleteExpiredFlag 
Write-Host "Taking decision from Flag Existance:"
if ($testFlagObj.FlagExists){
    Write-Host "-> Do action because Flag Exists"
}else{
    Write-Host "-> Confirmed Flag NOT Exist."
}

Write-Host "`r`nPrinting Object Result Details:"
$testFlagObj | Out-String | write-host

Write-Host "Test flag after expiring and deleting it automatically" -ForegroundColor Magenta
start-Sleep -Seconds 3
Write-Host "Taking decision from Flag Existance"
if((Test-Flag -flagPathFile $flagPathFile -expirationSeconds 2 -deleteExpiredFlag).FlagExists){
    Write-Host "-> Do action because Flag Exists"
}else{
    Write-Host "-> Confirmed Flag NOT Exist."
}



Write-Host "`r`n`r`n>>> Tests ignoring Expiration" -ForegroundColor Magenta
Write-Host "New un-expiring Flag" -ForegroundColor Magenta
New-Flag -flagPathFile $flagPathFile | Out-String | Write-Host

Write-Host "Test un-expiring Flag" -ForegroundColor Magenta
Write-Host "Taking decision from Flag Existance"
if((Test-Flag -flagPathFile $flagPathFile).FlagExists){
    Write-Host "-> Do action because Flag Exists"
}else{
    Write-Host "-> Confirmed Flag NOT Exist."
}

Write-Host "`r`nRemove Flag(Delete Flag)" -ForegroundColor Magenta
Remove-Flag -flagPathFile $flagPathFile | Out-String | Write-Host



Results

PS C:\>

>>> Tests with Expiring Flag

New flag - ignoring pre-existing flags expired in 2 seconds.

FlagPathFile       ExitCode ExitMessage
------------       -------- -----------
C:\Temp\MyFlag.txt        0 Ok



Test Flag before expiring - Asigning result to an object
Taking decision from Flag Existance:
-> Do action because Flag Exists

Printing Object Result Details:

FlagPathFile       FlagExists ExitCode ExitMessage
------------       ---------- -------- -----------
C:\Temp\MyFlag.txt       True        0



Test flag after expiring and deleting it automatically
Taking decision from Flag Existance
-> Confirmed Flag NOT Exist.
[DBG]: PS C:\a2\Proyectos\PowershellExamples\DBScripts\TBA> 


>>> Tests ignoring Expiration
New un-expiring Flag

FlagPathFile       ExitCode ExitMessage
------------       -------- -----------
C:\Temp\MyFlag.txt        0 Ok



Test un-expiring Flag
Taking decision from Flag Existance
-> Do action because Flag Exists

Remove Flag(Delete Flag)


FlagPathFile       ExitCode ExitMessage
------------       -------- -----------
C:\Temp\MyFlag.txt        0 Ok