andrej
andrej

Reputation: 587

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

Upvotes: 0

Views: 1486

Answers (2)

m0lochwalker
m0lochwalker

Reputation: 432

I cannot speak to your hashes, but the construct of the custom object looks pretty shaky. I would start with properly formatting the custom object with a Name/Value pair for each item you want in $outputs, and append $outputs directly with each iteration...

$outputs = @()

foreach ($comp in $maschines.name) { 

    $outputs += [pscustomobject]@{

        Prop1 = Get-VM -Name $comp | Select -ExpandProperty Value1
        Prop2 = Get-VM -Name $comp | Select -ExpandProperty Value2
        Prop3 = Invoke-Commmand -ComputerName $comp -Scriptblock {Get-Something | Select Something}

    } 

}

Upvotes: 0

Mark Wragg
Mark Wragg

Reputation: 23395

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 

Upvotes: 4

Related Questions