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.
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 format for PowerShell objects 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
​
PowerShell Inline Object Access
PowerShell Objects are usually the results of a query like the example below that pulls the information on Windows Services on a computer. All the data is in an object oriented format where it can by refernece using $_.Property.
​
Get-service | Where{$_.Status -eq "Running"}