Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
 

In this example, I'll go over the basics of creating your own objects and object arrays.

Why would you use this? Say you want to aggregate various values and bring them all together - like exporting them all to a CSV.

So for argument's sake, let's say we want the following information for your system:

  • Computer Name
  • Number of Processors
  • AD Logon Server
  • PowerShell Execution Policy

You could run each individual command and get the data one at a time, but why not bring them all together in one object?

Introducing Custom PS Objects!

 

To create a new object, we create a PowerShell variable - easy enough. But we need to tell the variable that it's going to be a PSObject.

$NewPSObject = New-Object PSObject

Now we have our new PSObject. But there's nothing in it. Let's fix that. 

What we're going to do is add members to the PSObject. On a basic level, all we're doing is adding a name and value to the PSObject. The value can be anything we want!

So, we call the new variable and pipe it to the Add-Member cmdlet.

$NewPSObject | Add-Member -Type NoteProperty -Name "Computer Name" -Value $ENV:COMPUTERNAME
$NewPSObject | Add-Member -Type NoteProperty -Name Processors -Value $ENV:NUMBER_OF_PROCESSORS
$NewPSObject | Add-Member -Type NoteProperty -Name "Logon Server" -Value $ENV:LOGONSERVER
$NewPSObject | Add-Member -Type NoteProperty -Name "Execution Policy" -Value $(Get-ExecutionPolicy)

Now, if we were to call $NewPSObject, we'll see something like this:

Computer Name Processors Logon Server Execution Policy
------------- ---------- ------------ ----------------
ITS-161225    8          \\BAGEL          RemoteSigned


So, we have everything together - all in one variable! Now you can do nifty things like pipe it to Export-CSV.

But what if we wanted to get that same data, but for every computer in your organization? Easy! We'll create an array!

$Array = @()

Then, we'll do a foreach loop and add the results of each new object to that array. Since I used local environmental variables - I have to pass that through Invoke-Command to get the values that I don't know.

foreach ($Computer in (Get-ADComputer).Name) {
    $NewPSObject = New-Object PSObject
    $NewPSObject | Add-Member -Type NoteProperty -Name "Computer Name" -Value $Computer
    $NewPSObject | Add-Member -Type NoteProperty -Name Processors -Value $(Invoke-Command -ComputerName $Computer -ScriptBlock {$ENV:NUMBER_OF_PROCESSORS})
    $NewPSObject | Add-Member -Type NoteProperty -Name "Logon Server" -Value $(Invoke-Command -ComputerName $Computer -ScriptBlock {$ENV:LOGONSERVER})
    $NewPSObject | Add-Member -Type NoteProperty -Name "Execution Policy" -Value $(Invoke-Command -ComputerName $Computer -ScriptBlock {Get-ExecutionPolicy})
    $Array += $NewPSObject
}

Now, if we call $Array, we get a nice tidy array of objects that we can sort, group and export!