Powershell';s Invoke命令赢得';是否为-ComputerName参数引入变量?

Powershell';s Invoke命令赢得';是否为-ComputerName参数引入变量?,powershell,powershell-2.0,powershell-remoting,Powershell,Powershell 2.0,Powershell Remoting,我在这里发牢骚,因为我似乎无法让它工作,我也不知道如何用谷歌搜索这个问题。我正在运行Powershell 2.0。这是我的剧本: $computer_names = "server1,server2" Write-Output "Invoke-Command -ComputerName $computer_names -ScriptBlock { Get-WmiObject -Class Win32_LogicalDisk | sort deviceid | For

我在这里发牢骚,因为我似乎无法让它工作,我也不知道如何用谷歌搜索这个问题。我正在运行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并运行该命令时,它工作得很好。如何将字符串变量强制转换为调用命令将接受的对象?提前谢谢

您的数组声明不正确。在字符串之间加一个逗号,并用管道将其连接到每个类似的字符串:

$computer_names = "server1", "server2";

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

    ...snip
您是否尝试过:

$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 
}
}

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 
}

如果您也从active directory获取一组计算机-如下所示:

$computers=Get ADComputer-filter{whatever}

确保记得选择/展开结果。。像这样:

$Computers=Get ADComputer-filter*|选择对象-ExpandProperty Name

然后


调用命令-ComputerName$Computers-ScriptBlock{Do Stuff}

,谢谢!我没想到要在上面每个人都做一个测试。这是我没见过的速记。但是,我避免声明数组,因为我不认为Invoke命令-ComputerName需要一个-相反,它需要一个由一个逗号分隔的计算机名列表,没有空格。我错了吗?回答我自己:看起来是这样。我刚刚阅读了该命令的帮助,它说它需要一个字符串[]。我只是脱离了示例,做了一个错误的假设。如果已经用计算机对象填充了名为
$computers
的变量(例如,使用
get-adcomputer
$computer\u-names=$computers.name
),那么填充数组的另一种方法就是这样。