The following script fails on the last line with 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 "."

However, when I enter this one-by-one into the console, it runs without issue.

I've added the Start-Sleep due to some timing issues... the session takes a few seconds to actually open. Any ideas why that line would fail only when this is running as a script?

  • What happens if you replace -computername "." with the actual hostname? How is the script being called? – user160910 Aug 8 '13 at 15:15
  • @GreggLeventhal Interesting... now I get Get-WmiObject : Access is denied. If I do that get-wmiobject call from my local computer, I get the same issue. So I guess that even though I've entered the session on the remote computer, the script stays in the scope of the local machine. – tnw Aug 8 '13 at 15:19

Enter-PSSession is intended only for interactive use. If you want to run commands on a remote system in a script (non-interactively), you'll need to use Invoke-Command instead. Please run Get-Help Invoke-Command -Full for more details.

| improve this answer | |
  • What he said. You'll also need to read up on how to pass local params into the remote session, which is super-easy in V3 and a bit of a hassle (but still not hard) in V2. – Trondh Aug 21 '13 at 20:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.