In a recent PowerShell ScriptingAnswers.com post, a member was asking about variables and whether they were “live” or linked to an actual object.The answer is “Yes and No, depending…” For example, consider this expression:
PS C:\> $s=get-service wsearch |
The $s variable holds the wsearch service object. I can check it’s status:
PS C:\> $s.status Running PS C:\> |
I could even stop it:
PS C:\> $s.stop() |
However, $s will still show a status of Running while the actual service shows that it was stopped.
PS C:\> $s.status Running PS C:\> get-service wsearch Status Name DisplayName ------ ---- ----------- Stopped WSearch Windows Search |
The $s variable is quasi-live but is really just a container for the service object as it existed when the object was created. If I had stopped the service after creating $s, $s would still show it running. What the forum member was after was a live or linked variable to the service object. Well we can’t use a variable, but because PowerShell is object based I can use a different type of object.
PS C:\> $s={get-service wsearch} |
$s is now a script block. To see the current object all I need to do is invoke it:
PS C:\> &$s Status Name DisplayName ------ ---- ----------- Running WSearch Windows Search |
I can use the variable in the pipeline:
PS C:\> &$s | stop-service -whatif What if: Performing operation "Stop-Service" on Target "Windows Search (WSearch)". |
Or, which is what the user was after, call methods that will affect the actual service object:
PS C:\> (&$s).stop() PS C:\> (&$s).status Stopped PS C:\> (&$s).start() PS C:\> (&$s).status StartPending PS C:\> (&$s).status Running PS C:\> |
Invoking the $s variable gives me the actual service object in its current and live state. I like efficiency and I can’t imagine it getting more efficient than that.
So even though a normal variable is merely a point in time snapshot, there are ways to create more lively PowerShell variables.
Actually a word of warning is warranted here. Using the scriptblock variable in the described fashion causes the creation of a new object with every single use.
The abandoned previous object does not get destroyed until you close that particular shell and this can lead to a very large accumulation of memory leaks when used in a loop.
Alexander Riedel