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:
Get-VMHost
)Get-VMHostSysLogServer
).How can I achieve this?
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:
Get-VMHost
(represented as the current pipeline item via $_
).$SysLog
@{ }
of the desired properties.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.