PowerShell Pause

Waiting is a game that can be played even with PowerShell. There are a few options when working PowerShell and pausing its operation to waiting for a process to complete. What purpose would this serve in PowerShell? One possible use is waiting for an executable to finish perhaps for a Windows update or another feature being installed. Another possible use would be to check a process or wait for an action to complete before continuing. In a previous post we covered Start-Sleep, so in this article we will cover two other possible methodologies.

Out-Null

Out-File can be added to the running of an Executable file to have PowerShell not advance until an executable has completed executing. This can be especially useful for long running
installation programs for certain Windows updates or prerequisites that may need to be installed for an application. In some cases this is better than trying to time a ‘Start-Sleep’ cmdlet with the installation as installation times on servers can vary depending on many factors which could be outside your control.
Example

Installing .NET 4.8. As it is a prerequisite for some applications, we would not want PowerShell to release and look like the application is installed completely when it is not. So what we can do is add the PowerShell cmdlet ‘Out-Null’ to an executable which will then pause PowerShell until the installation process completes like so:
[sourcecode language=”powershell”]
Write-Host "File: ndp48-x86-x64-allos-enu.exe installing…" .\ndp48-x86-x64-allos-enu.exe /quiet /norestart | Out-Null
[/sourcecode]
Now PowerShell will allow the installation of .NET 4.8 to complete and once that is done, it will allow further PowerShell commands to be run.

Do { } While ()

Do While creates a loop, essentially keeping PowerShell paused until a certain condition is met. This is especially useful for a scenario where you would not want PowerShell to keep processing until a full set of objects. Once all objects states have changed, then then script could continue.

Example

For this sample code below, we have a set of lines that will out PowerShell in a holding pattern until the variable $MoveCount is not at 0. The criteria is that the status of all mailbox moves needs to be ‘Completed’. When no more mailbox moves are other than Completed, then the Do While loop will exit.
[sourcecode language=”powershell”]
Do {
$MoveCount = (Get-MailboxMoveRequest | Where {$_.Status -ne 'Completed'}).Count
} While ($MoveCount -ne 0)
[/sourcecode]
After this code completes, we could then say generate a report of all mailbox moves, record the time they were completed and email the IT group about the move process. This would not be possible without some way of monitoring the moves and holding off until all were done.

Related Post

ConsistencyConsistency

Depending on your background or tendencies, coding may not come natural as it does for other people. I have found over time that one aspect in coding will make your