Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Monday, November 24, 2014

Adding properties to PowerShell Output

This morning on, I helped with a question about adding data to an output.  Essentially, there were two data sources and the user needed the data to be presented in one object so they could pipe it to Export-CSV.  The Select-Object cmdlet has the ability to add data to an object.  Take a look at this code.















$Servers= "Server1", "Server2"

$MasterArray = @()

ForEach($Server in $Servers)



    If(Test-Connection -quiet -computer $server)


    $Result=Get-Counter -Counter "\\$server\Processor Information(_Total)\% Processor Time"

    $Result | Select-Object -Property *,






This is the complete code.  What was missing was lines 9 and 10.  Lines 9 and 10 are actually the same line.

On line 9, I am using the comma to act as a line continuation character.  Line 10 is where the magic starts.  On line 9, we are piping the object stored in $Results to the Select-Object statement.  We have chosen to retain all of the properties of the object.  The “,” tells PowerShell that I want more.

Line 10 is a hash table.  The value of “N” is going to be the Name of the property.  The value of “E” is what to assign as the value of the property “Online”.  Yes, you need the extra {} as part of the expression.  In other words, let’s say that $Result has two properties; Name and Counter.  In this case, the question was how to add the result of  Test-Connection to the object.  Inside of the IF block is where we add the hash table to the Select-Object statement. The Hash table adds the third property of Online to the object.  If the connection was not made, we would not be getting any information.

For better design, consider using error handling and creating the object with both the computer name and setting the Online value to False.  That way you have a record of which clients were contacted and which ones were not.

No comments: