Powershell的Invoke-Command不会为-ComputerName参数接受变量?

问题描述 投票:6回答:4

我把头发拉到这里,因为我似乎无法让它发挥作用,我无法弄清楚如何谷歌这个问题。我正在运行Powershell 2.0。这是我的脚本:

$computer_names = "server1,server2"
Write-Output "Invoke-Command -ComputerName $computer_names -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}"
Invoke-Command -ComputerName $computer_names -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}

最后一个命令给出错误:

Invoke-Command : One or more computer names is not valid. If you are trying to 
pass a Uri, use the -ConnectionUri parameter or pass Uri objects instead of 
strings.

但是当我将Write-Output命令的输出复制到shell并运行它时,它可以正常工作。如何将字符串变量转换为Invoke-Command将接受的内容?提前致谢!

powershell powershell-v2.0 powershell-remoting
4个回答
5
投票

您错误地声明了数组。在字符串之间加一个逗号并将它管道为for-each,如:

$computer_names = "server1", "server2";

$computer_names | %{
   Write-Output "Invoke-Command -ComputerName $_ -ScriptBlock {

    ...snip

6
投票

Jamey和user983965是正确的,因为你的声明是错误的。但是foreach不是强制性的。如果您只修复这样的数组声明,它将起作用:

$computer_names = "server1","server2"
Invoke-Command -ComputerName $computer_names -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}

0
投票

你有没有尝试过:

$computer_names = "server1" , "server2"

foreach ($computer in $computer_names)
{
Write-Output "Invoke-Command -ComputerName $computer -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}"
Invoke-Command -ComputerName $computer -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}
}

0
投票

如果你从活动目录中获得一组计算机 - 就像这样:

$ computers = Get-ADComputer -filter {whatever}

确保你记得选择/扩展结果..像这样:

$ Computers = Get-ADComputer -filter * | Select-Object -ExpandProperty Name

然后...

Invoke-Command -ComputerName $ Computers -ScriptBlock {Do Stuff}

© www.soinside.com 2019 - 2024. All rights reserved.