Search code examples
powershellinvoke-command

powershell invoke-command to variable and write out as a table


I have the following code, from what I would like to get the output to

$output

and write-host at the end:

$outputs = @()
foreach ($comp in $maschines.name) { 
    $output = New-Object PSObject -Property @{
            invoke-command -computer comp3 -ScriptBlock { get-vm –VMName $using:comp | Select-Object VMId | Get-VHD | ft @{
            label="vm"; expression={$using:comp}}, 
            path,
            VhdType, 
            VhdFormat, 
            @{label="file(gb)"; expression={($_.FileSize / 1GB) -as [int]}}, 
            @{label="size(gb)"; expression={($_.Size / 1GB) -as [int]}} -AutoSize 
        }
    }
    $outputs += $output
}

$outputs

I get the error

Missing '=' operator after key in hash literal


Solution

  • The issue is coming from the New-Object cmdlet which is expecting a hash table be provided to the -Property parameter.

    I don't think you need New-Object at all to get what I think you're after.

    You might also want to consider using Select-Object instead of Format-Table and then using Format-Table at the end to give you more flexibility over how you can further manipulate the results if needed.

    You also can return the result of the ForEach directly rather than adding to an array, which is less efficient as the array is recreated each time:

    $output = foreach ($comp in $maschines.name) { 
        invoke-command -computer comp3 -ScriptBlock {
            get-vm –VMName $using:comp | Select-Object VMId | Get-VHD | Select-Object @{ label = "vm"; expression = {$using:comp} }, 
            path,
            VhdType, 
            VhdFormat, 
            @{label = "file(gb)"; expression = {($_.FileSize / 1GB) -as [int]} }, 
            @{label = "size(gb)"; expression = {($_.Size / 1GB) -as [int]} }
        }
    }
    
    $output | Format-Table -AutoSize