Share via

Powershell condition

Sara 441 Reputation points
2021-11-25T06:40:37.133+00:00

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 for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

MotoX80 37,696 Reputation points
2021-11-25T20:28:05.097+00:00

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




  
  

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.