I make use of custom objects constantly in PowerShell. Having the ability to easily combine and present data is incredibly powerful. Since I use them so much, I’ve found myself wanting to make them as fast and easy as possible to create. After much research and experimentation, I think I have created one of the single fastest and easiest ways of making custom objects in PowerShell – and I wanted to share with you. Ready?
$C=@("Column1 Column2 ColumnXX Column99")
$myObj=@();Function Add-ToObject{$C=($C -split ' ');$i=0;ForEach($R in $C){$P+=@{$R=$Args[$i]};$i++;};$Script:myObj+=[pscustomobject]$P}
Update: I managed to shrink this function down even further by collapsing some functions into others and making some other tweaks. If you think you can get this shorter, (even by a single character!), please share how in the comments:
$C="User ComputerName Email OS"
Function Add-ToObject{$args|%{$i++;$P+=@{$C.split(" ")[$i-1]=$_}};$Script:myObj+=@([pscustomobject]$P)}
To make the script a little easier to understand, here it is again, but this time in its full expanded form:
I’ve effectively gotten the process down to 2 lines for any number of custom properties! But it’s even better than that. You can ignore the second line entirely. Instead just concentrate on the first line where you define the columns you want in your custom object. If you want to add another column, just add it to the end separated by a space. If you want to remove a column, delete the name. That’s it! Let’s look at a real world example.
Imagine a scenario where you need to identify all of the users running Windows XP in your environment and send them an email saying you need to upgrade. To do this, you need to produce a list of all of the computers in your network, the operating system they run as well as the user that manages/owns it along with their email address. This information must come from two different cmdlets (Get-ADComputer and Get-ADUser). How can we combine these results into a single object for easy output?
Step 1) Copy and paste the two lines above at the top of your script and modify the column names and quantity to match your needs
Step 2) Write the code that generates the data that you need
Step 3) Once you have the data gathered, call the function Add-ToObject and pass in all the data you data you want. Since these are objects, this can be any kind of data
Step 4) Output the results from the variable $myObj. (You can change this if you want but I often find for quick work I’m doing, I just need a single object so sticking with a standard name is useful for smaller projects)
Continue reading