Powershell命令失败,返回“0”;无效命名空间";仅当作为脚本运行时,而不是在控制台中运行时

Powershell命令失败,返回“0”;无效命名空间";仅当作为脚本运行时,而不是在控制台中运行时,powershell,Powershell,以下脚本在最后一行使用Get WmiObject失败:无效命名空间: $password = ConvertTo-SecureString "password" -AsPlainText -Force $cred= New-Object System.Management.Automation.PSCredential ("domain\user", $password ) Write-Host "Entering PS Session..." Enter-PSSession -Computer

以下脚本在最后一行使用
Get WmiObject失败:无效命名空间

$password = ConvertTo-SecureString "password" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("domain\user", $password )
Write-Host "Entering PS Session..."
Enter-PSSession -Computer hyperVServer -Credential $cred
Start-Sleep -s 5
$server = "servername"

$query = "SELECT * FROM Msvm_ComputerSystem WHERE ElementName='" + $server + "'"
$VM = get-wmiobject -query $query -namespace "root\virtualization" -computername "."
但是,当我把它一个接一个地输入控制台时,它运行起来没有问题


由于一些时间问题,我添加了
开始睡眠
。。。会话实际打开需要几秒钟的时间。你知道为什么这一行只有在作为脚本运行时才会失败吗?

不知道为什么它在一个脚本中工作,而在另一个脚本中不工作,但我认为这与远程会话有关。下面是一个不需要远程会话,只需要计算机名的命令列表


还编辑了您的查询concat。

Enter-PSSession仅供交互使用。如果要在远程系统上以脚本(非交互方式)运行命令,则需要改用Invoke命令。有关详细信息,请运行Get-Help Invoke命令-Full

$password = ConvertTo-SecureString "password" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("domain\user", $password )
$server = "servername"
$query = "SELECT * FROM Msvm_ComputerSystem WHERE ElementName=$server"
$VM = get-wmiobject -query $query -namespace "root\virtualization" -computername hyperVServer -credential $cred