Whenever you start or stop a service, it may take some time for the service to actually adopt 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:

# wait 5 seconds for spooler service to stop
$serviceToMonitor = Get-Service -Name Spooler
$desiredStatus = [System.ServiceProcess.ServiceControllerStatus]::Stopped
$maxTimeout = New-TimeSpan -Seconds 5

try
{
  $serviceToMonitor.WaitForStatus($desiredStatus, $maxTimeout)
}
catch [System.ServiceProcess.TimeoutException]
{
  Write-Warning 'Service did not reach desired status within timeframe.'
}

You can use this chunk of code to respond to service changes triggered by outside systems, or double-check service status after own changes you committed to its settings.

Your learning points:

  • 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 our example showed how it can be used.
  • To discover other methods hidden in objects, try this:
# get some object 
$objects = Get-Process 

# dump the methods
$objects | Get-Member -MemberType *method* | Select-Object -Property Name, Definition

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU - with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!

Anonymous