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

标签 powershell powershell-2.0 powershell-remoting

我在这里拉头发,因为我似乎无法使它正常工作,而且我不知道如何用Google搜索这个问题。我正在运行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将接受的内容?提前致谢!

最佳答案

您对数组的声明不正确。在字符串之间放置一个逗号,并将其通过管道传递给每个字符串,例如:

$computer_names = "server1", "server2";

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

    ...snip

关于powershell - Powershell的Invoke-Command不会接受-ComputerName参数的变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10096336/

相关文章:

powershell - 退出 powershell 脚本后,通过 New-PSDrive 映射的网络驱动器消失

用于从文件夹列表中省略遍历访问被拒绝的文件夹的 Powershell 脚本

powershell - IIS 7.5 应用程序池/IIS 管理器 GUI 列 : Applications

powershell - Powershell让过去6个月内被禁用的AD用户感到困惑?

powershell - Server 2012 R2 缺少 PSReadline cmdlet?

powershell - 列出一个文件夹结构中不在另一个文件夹结构中的文件

Powershell - 在目录的长文件路径中查找嵌套文件夹的数量

powershell - 括号中的变量无法识别

powershell - PowerShell:控制台应用程序的远程执行失败

c# - 在 C# 中检查远程 PowerShell session 状态