Search code examples
powershellpowercli

PowerShell/PowerCLI reference to previous object


I am working on simple reporting one-liner and I can't get it to work.

I am retrieving the ESXi hosts by cmdlet Get-VMHost. Get-VMHost is piped into Get-VMHostSysLogServer.

As the output I get the Host and Port properties. I would like to display the following properties:

  • Name (from Get-VMHost)
  • Host and Port (both from Get-VMHostSysLogServer).

How can I achieve this?


Solution

  • Here's one solution, that builds a custom object with the properties that you want:

    Get-VMHost | ForEach-Object {
    
        $SysLog = $_ | Get-VMHostSysLogServer
    
        ForEach ($SysLogServer in $SysLog) {
            $Result = @{
                VMHost = $_.name
                SysLogHost = $SysLogServer.Host
                Port = $SysLogServer.Port
            }
            New-Object -TypeName PSObject -Property $Result
        }
    }
    

    Explanation:

    • Uses a ForEach-Object loop to iterate through each VM Host returned by Get-VMHost (represented as the current pipeline item via $_).
    • Gets the SysLogServers of each Host in to $SysLog
    • Loops through all SysLogServers, building a hashtable @{ } of the desired properties.
    • Uses New-Object to output an object using the properties in the Hashtable which is returned to the Pipeline.

    If you'd like to capture the results to a variable, just add $YouVar = before Get-VMHost.

    If you want to send on the results to another cmdlet that accepts pipeline input (such as Export-CSV) you can do that directly as the end, just append | Export-CSV Your.csv after the last closing }. This is the benefit of using ForEach-Object as the outer loop, it supports the pipeline.