3

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?

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Not sure why it works in one and not the other, but I assuming it's something to do with your remote session. Here's a list of commands that do not require a remote session, but rather just take a computer name. http://technet.microsoft.com/en-us/library/dd819505.aspx

$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

Edited your query concat too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.