cCogito.Test.ps1


[DscResource()]
class cWaitForFile
{

    [DscProperty(Key)]
    [string]$Path

    [DscProperty(Mandatory)]
    [Ensure]$Ensure

    [DscProperty()]
    [int]$RetryCount = 5

    [DscProperty()]
    [int]$RetryIntervalSec = 60
    
    [cWaitForFile] Get()
    {
        $this.Ensure = if ($this.Test()) { [Ensure]::Present } else { [Ensure]::Absent }
        return $this
    }

    [void] Set()
    {
        if ($this.Ensure -eq [Ensure]::Present)
        {
            for ($i = 0; $i -lt $this.RetryCount; $i++)
            {
                Write-Progress -Activity "Waiting for $($this.Path) to be present..." `
                    -PercentComplete ((100 / $this.RetryCount) * $i) `
                    -CurrentOperation "$($i + 1) / $($this.RetryCount)" `
                    -Status "Attempt"

                if (!(Test-Path $this.Path)) {
                    Write-Verbose "$this.Path not found, waiting..."
                    Start-Sleep -Seconds $this.RetryIntervalSec
                }
            }

            if (!(Test-Path $this.Path)) {
                throw "$($this.Path) not found."
            }
        }

        if ($this.Ensure -eq [Ensure]::Absent)
        {
            for ($i = 0; $i -lt $this.RetryCount; $i++)
            {
                Write-Progress -Activity "Waiting for $($this.Path) to be absent..."

                if (Test-Path $this.Path) {
                    Write-Verbose "$this.Path found, waiting..."
                    Start-Sleep -Seconds $this.RetryIntervalSec
                }
            }

            if (Test-Path $this.Path) {
                New-InvalidOperationException -Message "$this.Path found. Permanent failure."
            }
        }
    }
    
    [bool] Test()
    {
        if ($this.Ensure -eq [Ensure]::Present)
        {
            return Test-Path $this.Path
        }

        if ($this.Ensure -eq [Ensure]::Absent)
        {
            return !(Test-Path $this.Path)
        }

        return $false
    }

}

$c = New-Object cWaitForFile
$c.Ensure = [Ensure]::Present
$c.Path = 'C:\Windows\ativpsrm.bin'
$c.Get()

$c = New-Object cWaitForFile
$c.Ensure = [Ensure]::Present
$c.Path = 'C:\Windows\ativpsrm.bin'
$c.Test()

$c = New-Object cWaitForFile
$c.Ensure = [Ensure]::Present
$c.Path = 'C:\Windows\ativpsrm.bin'
$c.RetryCount = 1
$c.Set()