Monthly Archive

Categories

WMI cmdlets and credentials

If you’re working with the WMI cmdlets and need to pass credentials you’ll end up with a statement something like this

Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer -Credential $cred

 

If the computer name defaults to the local host or you use . or ‘localhost’ as the computer name you’ll get an error

PS> Get-WmiObject -Class Win32_ComputerSystem -ComputerName $env:COMPUTERNAME  -Credential $cred
Get-WmiObject : User credentials cannot be used for local connections
At line:1 char:1
+ Get-WmiObject -Class Win32_ComputerSystem -ComputerName $env:COMPUTER ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

 

You need to build in some logic to prevent credentials being used ig you’re working against the local machine.  One way to this is to create a bunch of Get-WmiObject statements and use if statements to decide which to use.

 

I think there’s a neater way if you use splatting

#$computer = $env:COMPUTERNAME
#$computer = 'localhost'
#$computer = '.'
$computer = 'server02'

$params = @{
    'Class' =  'Win32_ComputerSystem '
    'ComputerName' = $computer
}

switch ($computer){
    "$env:COMPUTERNAME" {break}
    'localhost' {break}
    '.'   {break}
    default {$params += @{'Credential' = $cred}}
}

Get-WmiObject @params

 

Splatting involves creating a hash table of the parameters and their values. You can then use a switch statement to decide if computer matches any of the local name variants. If it doesn’t then add the credential

 

You could extend this slightly to cope with not having a computer name  in the initial set of params and only add it if required

$params = @{
    'Class' =  'Win32_ComputerSystem'
}

if ($computer) {
    $params += @{'ComputerName' = $computer}
   
    switch ($computer){
        "$env:COMPUTERNAME" {break}
        'localhost' {break}
        '.'   {break}
        default {$params += @{'Credential' = $cred}}
    }
}

Get-WmiObject @params

 

Then you only test the computer name if you need to.

Comments are closed.