Ever wanted to have a custom PowerShell Object with custom property attributes? This can make your console output cleaner, and I also find it very useful when using Export-CSV.
For the purpose of this post I’ve created an object that has 3 properties: “Hostname”, “Enabled”, and “NetworkUp”. The “Hostname” property will hold the name of a computer, the “Enabled” property will tell us if its enabled in Active Directory, and the “NetworkUp” property will tell us if we can ping it by name. Here’s the output:
The script works by creating individual custom objects, and adding them to an array like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$Computers = Get-ADComputer -Filter * # Get a list of computers from AD $RetArray = @() # Declare the Return Array (To hold the custom objects) ForEach ($Computer in $Computers) # Iterate through the computers { # Declare a new object and add properties/values to it $object = New-Object -TypeName System.Object $object | Add-Member -type NoteProperty -name Hostname -Value $Computer.Name $object | Add-Member -type NoteProperty -name Enabled -Value $Computer.Enabled $object | Add-Member -type NoteProperty -name NetworkUp -Value (Test-Connection $Computer.Name -Quiet -Count 1 -TimeToLive 5) # Add the custom object to the array $RetArray += $object } |
Cool! Want to work with 1 property in particular? You can do the following:
1 2 3 |
$RetArray.Hostname $RetArray.Enabled $RetArray.NetworkUp |
Or to work with individual items inside the array:
1 2 3 |
$RetArray[0].Hostname $RetArray[1].Enabled $RetArray[2].NetworkUp |
For me, the best part of using custom objects is the ability to export their data straight to CSV. Sometimes when working with custom objects and exporting to CSV you dont get the output you expect. E.G you just see type information. Using this method works seamlessly:
1 |
$RetArray | Export-CSV -Path C:\Users\MyUser\Desktop\MyCSV.csv -NoTypeInformation |