4

#PSTip Refreshing service objects

When you assign the result of a service query to a variable, you must take into account one very important thing – the result is just a snapshot of the service state for a specific point in time.

PS> $svc = Get-Service -Name W3SVC
PS> $svc

Status   Name               DisplayName
------   ----               -----------
Running  W3SVC              World Wide Web Publishing Service

Here you can see that the service Status is ‘Running’. However, if the state has been changed outside your script (you can simulate it by stopping the service via the services.msc MMC snap-in), the state of your variable will still show ‘Running’ and your script may fail or perform steps that are not to be run in the current state.

To have the most fresh settings of the service before making such descions you can re-query the service, but there’s a better way, use its Refresh method.

$svc.Refresh()

Calling the Refresh method refreshes the service property values to their current values.

Filed in: Columns, Tips and Tricks Tags: , ,

4 Responses to "#PSTip Refreshing service objects"

  1. pamarths says:

    That a very cool tip.

  2. Chris K. says:

    Excellent tip! Explains exacting what I thought I was experiencing.

    But since this is true, then what is the purpose for .WaitForStatus since it can never work?

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: