Waiting Loop

PowerShell is a pretty flexible language. We can perform many tasks to make our job easier with it. What if there was a way for PowerShell to wait for a condition to change to true in order to set off an additional set of steps. For this example we have a PowerShell script that is in charge of monitoring the status of some mailbox migrations. Once the migrations complete, we want the script to send out a notification. The triggering criteria for this example would be if the number of jobs whose status did not equal completed was ‘0’.

The Code

The code below simply looks for the status of move requests. If no jobs show as ‘In Progress’ then a notification email is sent. Th reason this criteria was used is that if a move requests fails, completed or otherwise errors out, then the status will not be ‘In progress’ and the progress of the job will have stopped. The script then serves it’s purpose in that we know that no jobs are in flight or moving.
[sourcecode language=”powershell”]
$MoveRequests = Get-MoveRequest
Do {
$JobsInFlight = 1
$MoveRequests = Get-MoveRequest
Foreach ($MoveRequest in $MoveRequests) {
If ($MoveRequest.Status -eq 'InProgress') {
$JobsInFlight++
}
}
If ($JobsInFlight -eq 1) {
Write-Host 'All Mailbox moves are processed …' -ForeGroundColor Green
Write-Host ' '
$JobsInFlight = 0
} Else {
$JobsInFlight = $JobsInFlight -1
Write-Host 'Still Processing mailbox moves …' -ForeGroundColor Yellow
Write-Host "Jobs in progress = $JobsInFlight"
}
} While ($JobsInFlight -gt 0)
$SMTPServer = '192.168.0.25'
$To='damian@practicalpowershell.com'
$From = 'noreply@practicalpowershell.com'
$Subject = 'Move Completion Notification'
$Body = 'All moves are complete!'
Send-MailMessage -To $To -From $From -Subject $Subject -Body $Body -SmtpServer $SMTPServer
[/sourcecode]

Adding Status Totals

If we want, we could add code to check for the status of each completion type. This notification would have tallys for completed, failed and other non in-progress. These lines can be added just before this line:
[sourcecode language=”powershell”]
$SMTPServer = '192.168.0.25'
[/sourcecode]
Code lines to add:
[sourcecode language=”powershell”]
Foreach ($MoveRequest in $MoveRequests) {If ($MoveRequest.Status -eq 'Failed') {$FailedCount++}
Foreach ($MoveRequest in $MoveRequests) {If ($MoveRequest.Status -eq 'Completed') {$CompletedCount++}
[/sourcecode]
And that’s it. Now we have a script that will continuously run and only end when all mailbox moves are either failed or completed.

Related Post

Compare-ObjectCompare-Object

Depending on what tasks you perform with PowerShell, you may never need Compare-Object. However, when you need it, you will find it immensely helpful and problematic at the same time.