Powershell – Test for Localhost in Powershell

powershellremote-access

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?

Best Answer

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 }