How to use foreach loop inside Invoke-Command in PowerShell?

后端 未结 1 1903
一生所求
一生所求 2021-01-06 11:37

In the below code I was using $scripts variable to iterate through a foreach loop inside the Invoke-Command statement. But $scri

1条回答
  •  伪装坚强ぢ
    2021-01-06 12:20

    I'm going to assume that the syntax errors in your code are just typos in your question and are not present in your actual code.

    The problem you describe has nothing to do with the nested foreach loop. It's caused by the double quotes you put around the arguments you pass to the invoked scriptblock. Putting an array in double quotes mangles the array into a string with the string representations of the values from the array separated by the output field separator defined in the automatic variable $OFS (by default a space). To avoid this behavior don't put variables in double quotes when there is no need to do so.

    Change the Invoke-Command statement to something like this:

    Invoke-Command -ComputerName $Server -Credential $cred -ScriptBlock {
        Param($server, $scripts, $url)
        ...
    } -ArgumentList $server, $scripts, $url
    

    and the problem will disappear.

    Alternatively you could use the variables from outside the scriptblock via the using scope modifier:

    Invoke-Command -ComputerName $Server -Credential $cred -ScriptBlock {
        foreach ($script in $using:scripts) {
            echo "$script"
        }
    }

    0 讨论(0)
提交回复
热议问题