8

I have a powershell script that calls Get-WmiObject with -Credential. However, this errors out if I am running it against the local machine:

Get-WmiObject : User credentials cannot be used for local connections

What is the proper way to add an if localhost logic to avoid this error? Or is there a better way?

Nic
  • 13,425
  • 17
  • 61
  • 104
Kyle Brandt
  • 83,619
  • 74
  • 305
  • 448

2 Answers2

3

You could always query the local IP through WMI and store it in $localIP and then match that against whatever address is currently next in your pipeline or array:

if ($localIP -eq $otherIP) { get-wmiobject without -credential }    
else { existing query }
MDMarra
  • 100,734
  • 32
  • 197
  • 329
2

If you wrap it in a try catch block with erroraction stop on the first command, it will trap the error and run the catch block without credentials.

Try
{
Get-WmiObject -Credential domain\user -ComputerName localhost -class Win32_BIOS -erroraction Stop
}
Catch
{
Get-WmiObject -ComputerName localhost -class Win32_BIOS
}
Christopher
  • 1,673
  • 12
  • 17
  • Does PS allow me to catch a particular Exception for the error I am getting? – Kyle Brandt Aug 09 '11 at 22:58
  • If you know the .NET Exception class you can do it like this... catch [System.Net.SomeWMIExceptionClass] { code goes here } – Christopher Aug 09 '11 at 23:06
  • I am wrong. Per this question http://stackoverflow.com/questions/3097785/powershell-ioexception-try-catch-isnt-working and some testing I did, PowerShell wraps the exception so you cannot catch specific errors. – Christopher Aug 10 '11 at 15:03