2020 | Scott W. Head  |  Sr. Systems Admin | Certified Microsoft Windows Server Administrator

PowerShell Objects

PowerShell Objects can be a great help when handling data. I usually use these to store information and save it to an array for later use of export to a CSV file for reporting. Below is a older version of creating a PowerShell object and assigning values, this works on PowerShell 2.0 and above. I use this a lot since some of my servers are still 2008R2 and don’t have the newer PowerShell installed.

Good Article on Object and the Differences 

This is an older school style of a PowerShell Object:

$Obj=New-Object PSObject 
$Obj |Add-Member NoteProperty MyName ("Scott Head")
$Obj |Add-Member NoteProperty MyHome ("Redondo")
$Obj |Add-Member NoteProperty MyCar ("Mustang")
$Obj |Add-Member NoteProperty MyJob ("Chevron Oil")

Return $Obj 

 

A Newer style / format for objects is shown as below:
          

#Declare Array For Storing Multiple Object Data
$MyObjectArray=@()

#Create and Populate Object Data and Assign Value to Variable
$MyObjectVariable=[PSCustomObject]@{
FirstName = "SCOTT"         
LastName = "HEAD"
Location="Redondo"        
Job="Sr. Systems Admin"        
SomeNUmber=455   
}  
  

#Create and Populate Object Data and Assign Value to Variable
$MyObjectVariable2=[PSCustomObject]@{
FirstName = "Joseph"         
LastName = "Smith"
Location="Venice Beach"        
Job="Teacher"        
SomeNUmber=5 
}    
  

#Populate Array With Object Data             
$MyObjectArray+=$MyObjectVariable2
$MyObjectArray+=$MyObjectVariable
 

#Access A Property of the Object                 
Write-Output $MyObjectArray.SomeNumber