Categories

Meta

Pimp Your Output: Use Objects

Did you ever create a script, and when it was all done, rewrite a large part of it to change the way the output is shown, saved or printed? If you use the power of Powershell in a smart way, you will never have to again.

One of the great powers of Windows Powershell, is the way everything you use is an object. The output of every single Powershell cmdlet is an object or a collection of objects. This fact allows you to easily filter, sort or format the output of a command by piping is to Where-Object, Sort-Object or one of the Format cmdlets.

Now why don’t you write your scripts in the same way? Think for a minute about what kind of objects your output should be and what properties they should have. Then build these objects in your script. When you run your script, dot-source is (preceed the path to your script by a DOT and a SPACE). This way, all variables set in the script become global variables, which means you can access them after running your script. Either interactively, or by running another script.

This is the way to build a collection of objects in a script:

$myCol = @()

$collection = …

ForEach ($item in $collection)

{

$myObj = “” | Select Name, Property1, Property2

$myObj.Name = …

$myObj.Property1 = …

$myObj.Property2 = …

$myCol += $myObj

}

$myCol

First you create an empty array to hold your collection:

$myCol = @()

You grab the collection of object you need to manipulate to get your output values and loop through them (e.g.: Get-QADServer to get the servers in your domain):

$collection = …

ForEach ($item in $collection)

{

…

}

Then you build an empty object to represent your output item and define which properties it should have:

$myObj = “” | Select Name, Property1, Property2

You then proceed with your script to get the output values you need (e.g.: do a WMI query to a remote server to get disk space information) and set the values to the appropriate properties of your output object:

$myObj.Name = …

$myObj.Property1 = …

$myObj.Property2 = …

When your output object is done, you add it to the output collection and the loop will restart:

$myCol += $myObj

After running the script (don’t forget to dot-source it: PS D:>. D:scriptsmyscript.ps1), you can manipulate the output collection to save or print it: