Ok, maybe I’m not Lady Macbeth dealing with a guilty conscience but there are times I have to get things out of my system, like information via PowerShell. Often I want to store the results of a cmdlet in a variable for additional processing. Usually I do something like this:
$myProcesses=get-process
An alternative is to use one of the common paramaters, -OutVariable. With this parameter I can achieve the same result with this expression:
get-process -outvariable myProcesses
I can then access $myProcesses just as I normally would. You only need to specify the variable name (myProcesses, not the variable $myProcesses). If you don’t want to see the cmdlet output because you’re going to manipulate the result simply pipe the output to null.
get-process -outvariable myProcesses | out-null
Fundamentally there’s not much difference, unless you want to streamline code like this:
get-process -outvariable myProcesses | out-null ;write-host $myProcesses.count processes
This will display a message like: 65 processes
One thing to be careful of is where you use -OutVariable. Try this code and look at $result.
get-process -outvariable result | Where {$_.name -eq "svchost"}
On the console you’ll see something like this:
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
137 3 1496 3396 35 14.72 904 svchost
520 14 2304 4128 38 69.20 980 svchost
1878 52 34152 43756 251 862.52 1116 svchost
106 6 1448 2708 29 92.58 1352 svchost
162 3 3240 4036 38 22.28 1412 svchost
173 5 2104 3404 36 19.10 1428 svchost
106 3 1316 2952 34 54.13 2856 svchost
But if you look at $result you’ll see it shows every process. Why? The OutVariable parameter is storing output of the Get-Process cmdlet and storing the output in $result. What you really need it to use OutVariable with the Where-object cmdlet like this:
get-process | Where {$_.name -eq "svchost"} -outvariable result | out-null
Now if you look at $result you’ll get the filtered results. Using OutVariable won’t change the world but it might make it help condense your PowerShell expressions.