如何在 PowerShell 中的 Invoke-Command 中使用 foreach 循环?

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

在下面的代码中,我使用 $scripts 变量来遍历 Invoke-Command 语句中的 foreach 循环。但是 $script 值没有正确替换,结果似乎是 "count.sql size.sql" 的单个字符串。如果在 Invoke-Command 循环之外定义,foreach 循环将正确执行。

有什么特别的方法可以在 Invoke-Command 中定义 foreach 循环吗?

$scripts = @("count.sql", "size.sql")
$user = ""
$Password = ""
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword

foreach ($server in $servers) {
    Invoke-Command -ComputerName $Server -Credential $cred -ScriptBlock {
        Param($server, $InputFile, $scripts, $url)

        foreach ($script in $scripts) {
            echo "$script"
    } -ArgumentList "$server,"$scripts","$url"
}

我假设您代码中的语法错误只是您问题中的错别字,实际代码中不存在。

您描述的问题与嵌套foreach循环无关。这是由您在传递给调用的脚本块的参数周围加上双引号引起的。将数组放在双引号中会将数组破坏成一个字符串,其中数组中的值的字符串表示形式由自动变量 $OFS 中定义的 output field separator 分隔(默认情况下为 space) .为避免这种行为,不要在没有必要时将变量放在双引号中。

Invoke-Command 语句更改为如下内容:

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

问题就会消失。

或者,您可以通过 using scope modifier:

使用脚本块外部的变量
Invoke-Command -ComputerName $Server -Credential $cred -ScriptBlock {
    foreach ($script in $<b>using:</b>scripts) {
        echo "$script"
    }
}