Whenever you start or stop a service, it may take some time for the service to actually reached the desired state or it can of course fail. When you use Stop-Service, PowerShell waits until the desired service state is confirmed. If you want to respond to service changes initiated elsewhere, here is some monitoring code that pauses PowerShell until the desired service status is reached:
$MonitorService = Get-Service -Name Spooler
$PreferredStatus = [System.ServiceProcess.ServiceControllerStatus]::Stopped
$MaxTimeout = New-TimeSpan -Seconds 10
Write-Warning "Service did not reach the preferred status in a timely fashion."
You can use this PowerShell code to respond to service changes triggered by outside systems, or double-check service status after own changes you committed to its settings.
Most objects that you get from cmdlets (like Get-Service)have a number of useful methods. All service objects feature the WaitForStatus method, for example, and in the example above showed how it can be used.
To discover other methods hidden in objects, just try this:
$Objects = Get-Process
$Objects | Get-Member -MemberType *method* | Select-Object -Property Name, Definition
I really like to hear what you have to say about this article:
- Was this article helpful for you or do you have any questions?
- Do you have additions, suggestions or any other ideas?
- Just let me know by leaving a comment below.
Thank you for spending some time at my site and in my blog. I hope you come to visit again soon 😉