2017-09-06 46 views
0

在下面的代码中,我使用$scripts变量遍历Invoke-Command语句中的foreach循环。但$script值不能正确替换,并且结果似乎是单个字符串,因为“count.sql size.sql”。如果在Invoke-Command循环之外定义,则foreach循环正在正确执行。如何使用PowerShell中的Invoke-Command内的foreach循环?

是否有任何特定的方式来定义foreach循环内Invoke-Command

$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" 
} 
+0

这个脚本does not看起来完整。你似乎没有正确地调用服务器上的可变参数 – ArcSet

+0

,因为你的编辑看起来像你的参数列表是错误的。您正在使用“在他们周围将所有变量声明为字符串。将参数列表更改为 -ArgumentList $ server,$ scripts,$ url 另外您还没有按顺序声明所有的arugments ....服务器,输入文件,脚本,URL。目前$ Scripts是= to $ inputfile – ArcSet

+0

'-argumentList'参数也看起来被错误地放置,它当前在脚本块内 – andyb

回答

0

我打算假设您的代码中的语法错误只是您的问题中的拼写错误,并不存在于您的实际代码中。

您描述的问题与嵌套的foreach循环无关。它是由你传递给被调用的脚本块的参数引起的双引号造成的。将数组放入双引号将数组转换为一个字符串,其中字符串表示由自变量$OFS(缺省为空格)中定义的output field separator分隔的数组中的值。为了避免这种行为,当不需要时,不要将变量放在双引号中。

更改Invoke-Command声明是这样的:

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

,问题就会消失。

另外,您可以通过usingscope modifier使用从脚本块以外的变量:

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