Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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
up vote 5 down vote accepted

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.

share|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 posting your answer, you agree to the privacy policy and terms of service.

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