Powershell命令只有在作为脚本运行时才会失败,而“无效的命名空间”则不会在控制台中运行

以下脚本在Get-WmiObject : Invalid namespace的最后一行失败Get-WmiObject : Invalid namespace

 $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 "." 

但是,当我一个一个地input到控制台时,它运行没有问题。

由于某些计时问题,我添加了Start-Sleep …会话需要几秒钟才能打开。 任何想法为什么只有当这个脚本作为脚本运行时,该行才会失败?

Enter-PSSession仅用于交互式使用。 如果要在脚本中以非交互方式在远程系统上运行命令,则需要使用Invoke-Command。 请运行Get-Help Invoke-Command -Full以获取更多详细信息。