I have a PS scrips as below, and I am trying to rewrite as, the script should execute only if the below condition exists for 10 mins.
That's not much of script, you're just assigning a string of "Enabled|Success" to a variable.
Here's an example of how you can loop and test a variable to see if it equals a given value for a given amount of time.
$SyncStatusNotMatch = @(
"Enabled"
"Success"
) -join "|"
$TestTime = 2 # How long shoud the condition be true before we do something
$MaxTime = 3 # How long to run before we give up?
$TestDate = Get-Date
$MaxDate = Get-Date
$ShouldWeWait = $true
While ($ShouldWeWait) {
Start-Sleep -Seconds 5 # Delay unil we should test again
# Do something here to refresh $SyncStatusNotMatch
# $SyncStatusNotMatch = ??????
If($SyncStatusNotMatch -eq "Enabled|Success" ) { # What do we look for???
if ((New-TimeSpan –Start $TestDate –End (get-date)).Minutes -gt $TestTime) {
Write-Host "The condition has been true for more than $TestTime minutes."
Write-Host "This is what we've been waiting for."
# do something here
$ShouldWeWait = $false # We are done with this process
} else {
Write-Host "The condition is true but not for enough time."
}
} else {
$TestDate = Get-Date # reset the clock
Write-Host "The condition is not true."
}
if ((New-TimeSpan –Start $MaxDate –End (get-date)).Minutes -gt $MaxTime) {
Write-Host "We've been running too long."
Write-Host "Giving up."
$ShouldWeWait = $false
}
}
Write-Host "Process complete."