question

Sara925 avatar image
0 Votes"
Sara925 asked MotoX80 answered

Powershell condition

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. Any ideas on how to achieve that ?

$SyncStatusNotMatch = @(
"Enabled"
"Success"
) -join "|"

windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

MotoX80 avatar image
0 Votes"
MotoX80 answered

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."




5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.