Search code examples
powershellforeachinvoke-command

powershell foreach name execute invoke-command


I have the folowing code that outpusts names:

foreach ($comp in $maschines.name) { $comp }

but the folowing does not work, why?

foreach ($comp in $maschines.name) { invoke-command -computer comp1 -ScriptBlock { get-vm –VMName $comp | Select-Object VMId | Get-VHD | ft path } }

Solution

  • try the following:

     foreach ($comp in $maschines.name) { invoke-command -computer comp1 -ScriptBlock { get-vm –VMName $using:comp | Select-Object VMId | Get-VHD | ft path } }
    

    added the using: to your scriptblock to make use of that local variable you want to use on that other computer.