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?

link|improve this question

78% accept rate
How are you passing in the computername parameter? – Christopher Aug 9 '11 at 20:09
@Christopher: By IP (10.x.x.x), don't have much control over that as an application runs it. – Kyle Brandt Aug 9 '11 at 20:20
feedback

2 Answers

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 }
link|improve this answer
feedback

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
}
link|improve this answer
Does PS allow me to catch a particular Exception for the error I am getting? – Kyle Brandt Aug 9 '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 9 '11 at 23:06
I am wrong. Per this question stackoverflow.com/questions/3097785/… and some testing I did, PowerShell wraps the exception so you cannot catch specific errors. – Christopher Aug 10 '11 at 15:03
feedback

Your Answer

 
or
required, but never shown

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