Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question
    
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
add comment

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 }
share|improve this answer
add comment

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
}
share|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
add comment

Your Answer

 
discard

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.