Tag Archives: Output variable and console

Output to variable and console

I have a confession to make, I’m a PowerShell addict!

You don't say

I recently got a twitter account, not to tweet per se, but to get more PowerShell updates! Man! talk about real-time updates! It’s almost a day-job keeping up with the tweets!!!

So I was reading a blog by Stephen Owen aka FoxDeploy when I stumbled on a cmdlet I haven’t heard of: Tee-Object. See this is why you should read and not just scan blogs, you might learn something new… 😉

What’s the Tee-Object for? Eh, get-help Tee-Object much? Ok so Tee-Object saves command output in a file or variable and also sends it down the pipeline.

Hey I remember reading about saving results to a variable while sending output to the console on powershell.com some time back. Turns out there more than one way to get output to a variable and console. 🙂

Option 1 use parentheses
Pretty straightforward:

($results = Get-Service)

Option2 use -OutVariable
Ok I’ll admit I haven’t used this one much. When using the -OutVariable be sure to omit the “$” char or you’ll get an error. To see what’s been stored just type in the variable using, yes, $variablename, so in our case $TotalProcs and $SelectedProcs.

(Get-Process -OutVariable TotalProcs |
Select-Object ProcessName,Handles -OutVariable SelectedProcs)

$TotalProcs
$SelectedProcs

Option 3 use the Tee-Object
Last but not least the Tee-object. This will definitely help with sending data to a variable or file.

Get-Process |
Tee-Object -Variable Processes1 |
Select-Object ProcessName,Handles,Id |
Tee-Object -Variable Processes2
 
$Processes1
$Processes2

Think of the possibilities! How many times have you stored results in arrays to send to out-gridview to then later on send to export-csv? I like the third examples from get-help appending data to a cumulative file while send current results to a different file. Nice! Tee-Object reminds me of the pipe game… good times! 🙂

So there you have it, output to variable and console in three different flavors! Here’s a recap of all three:

#region Option 1 use Parentheses
($results = Get-Service)
#endregion

#region Option 2 OutVariable
(Get-Process -OutVariable TotalProcs|
Select-Object ProcessName,Handles -OutVariable SelectedProcs) 

$TotalProcs
$SelectedProcs
#endregion

#region Option 3 Tee-Object
Get-Process |
Tee-Object -Variable Processes1 |
Select-Object ProcessName,Handles,Id |
Tee-Object -Variable Processes2

$Processes1
$Processes2
#endregion

Hope it’s worth something to you,

Ttyl,

Urv