【问题标题】:How to use foreach loop inside Invoke-Command in PowerShell?如何在 PowerShell 的 Invoke-Command 中使用 foreach 循环?
【发布时间】:2018-02-14 09:51:00
【问题描述】:

在下面的代码中,我使用$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"
}

【问题讨论】:

  • 这个脚本看起来不完整。您似乎没有正确调用服务器上的变量
  • 因为您的编辑看起来您的参数列表是错误的。您通过使用围绕它们的 " 将所有变量声明为字符串。将参数列表更改为 -ArgumentList $server, $scripts, $url 此外,您没有按顺序声明所有参数....服务器、输入文件、脚本、URL。目前 $Scripts 是 = 到 $inputfile
  • -argumentList 参数看起来也放置不正确。它目前在脚本块内。
  • 似乎问题出在 ArgumentList 中的双引号..,删除 qoutes 后它工作正常。感谢您的回复:) 我们可以在调用命令脚本块中定义新变量吗?如果我定义,那么它显示错误,因为 param() 无法识别。如何在调用命令块中定义新变量?
  • 您发布的代码显然不可能成功运行。嵌套的 foreach 循环缺少右大括号,-ArgumentList 参数的第一个参数缺少右双引号。

标签: powershell powershell-4.0


【解决方案1】:

我将假设您代码中的语法错误只是您的问题中的拼写错误,并且不会出现在您的实际代码中。

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

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 $using:scripts) {
        echo "$script"
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 2014-10-13
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    相关资源
    最近更新 更多