#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.


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

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts