如何在 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
循环将正确执行.
In the below code I was using $scripts
variable to iterate through a foreach
loop inside the Invoke-Command
statement. But $script
values are not replacing properly and outcome seems to be single string as "count.sql size.sql". The foreach
loop is executing properly if defined outside the Invoke-Command
loop.
在Invoke-Command
中定义foreach
循环有什么特别的方法吗?
Is there any particular way to define foreach
loop inside 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"
}
推荐答案
我将假设您代码中的语法错误只是您问题中的拼写错误,而不存在于您的实际代码中.
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.
您描述的问题与嵌套的 foreach
循环无关.这是由您在传递给调用的脚本块的参数周围加上双引号引起的.将数组放在双引号中会将数组重整为一个字符串,其中数组中的值的字符串表示由 输出字段分隔符 定义在自动变量$OFS
(默认为空格).为避免这种行为,不要在不需要时将变量放在双引号中.
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.
将 Invoke-Command
语句更改为如下所示:
Change the Invoke-Command
statement to something like this:
Invoke-Command -ComputerName $Server -Credential $cred -ScriptBlock {
Param($server, $scripts, $url)
...
} -ArgumentList $server, $scripts, $url
问题就会消失.
或者,您可以通过 using
范围修饰符:
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"
}
}
这篇关于如何在 PowerShell 中的 Invoke-Command 中使用 foreach 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!