This example of PowerShell code shows how to output objects from your own functions. The basic tasks you do to accomplish this in your function are:
- Assemble the values into a hash table
- Create an object using that hash table
- Output the object
Once you do this, then you can treat your output as you would any other object in PowerShell.
- Assemble the values into a hash table
- See my example below, it is the lines like $Properties = @{…}
- More info at about_Splatting
- Create an object using that hash table
- See my example, the line starting with $Object = New-Object…
- Output the object
- Simply Write-Output $Object
# Example Function function Get-SystemInfo { # Prepare the info $OS = Get-CimInstance -ClassName Win32_OperatingSystem # for FreePhysicalMemory, Caption, PSComputerName, SystemDrive $LoadPercentage = (Get-CimInstance -ClassName Win32_Processor).LoadPercentage $ProcessCount = (Get-Process).Count $SystemDrive = Get-CimInstance -ClassName Win32_LogicalDisk -filter "Name = '$($OS.SystemDrive)'" $ComputerSystem = Get-CimInstance -ClassName Win32_ComputerSystem # Prepare the properties in a hash table $Properties = @{ ComputerName = $ComputerSystem.DNSHostName; Domain = $ComputerSystem.Domain; FreePhysicalMemory = "{0:n0}" -f ($OS.FreePhysicalMemory /1KB) + " MB"; OS = $OS.Caption; LastBootUpTime = $OS.LastBootUpTime; LoadPercentage = $LoadPercentage; ProcessCount = $ProcessCount; SysVolFree = "{0:n1}" -f ($SystemDrive.FreeSpace /1GB) + " GB" } # Create an object using the properties $Object = New-Object -TypeName PSObject -Property $Properties # Output the object Write-Output $Object } # Example Usage # Using the results, put them into an object "$Result" $Result = Get-SystemInfo # Access the values inside the object $Result.LastBootUpTime
One thought on “How to output objects from your own PowerShell functions”