Currently I´m building PowerShell WMI Explorer and because of this tool supports alternate credentials, then I thought how can I simplify my Get-WmiObject queries and the solution is Splatting 🙂

WMI_Explorer_Authentication

PowerShell splatting allows you to create Function or CMDLET parameters dynamically. Below example shows how you can build dynamically Get-WmiObject parameters. You can use this script to query WMI information from the local machine or from the remote computer and if necessary you can also add alternate credentials.

Function Create-Cred
{
    Param(
         $Username,
         $Password
         )
   
   Try{
        $Pass = ConvertTo-SecureString $Password -AsPlainText –Force -ErrorAction Stop
        Try{
            New-Object -typename System.Management.Automation.PSCredential -ArgumentList $Username,$Pass -ErrorAction Stop
        }
        Catch{
            $_.Exception.Message
        }
   }
   Catch{
        $_.Exception.Message
   }
   
}

Function Get-WMInformation
{
    Param(
         [Parameter(Mandatory=$True,HelpMessage="Please Enter NameSpace")]
            $NameSpace,
         [Parameter(Mandatory=$False,HelpMessage="Please Enter Authentication Level")]
         [ValidateSet("Default","None","Connect","Call","Packet","PacketIntegrity","PacketPrivacy")]
            $AuthentLvl = "Default",
         [Parameter(Mandatory=$False,HelpMessage="Please Enter User Name")]
            $Username,
         [Parameter(Mandatory=$False,HelpMessage="Please Enter User Password")]
            $Password,
         [Parameter(Mandatory=$False,HelpMessage="Please Enter computer name")]
            $ComputerName = "Localhost",
         [Parameter(Mandatory=$True,HelpMessage="Please Enter WMI Class")]
            $Class
         )

    $SP = @{}
    $SP['ComputerName'] = $ComputerName
    $SP['Authentication'] = $AuthentLvl
    $SP['NameSpace'] = $NameSpace
    $SP['Class'] = $Class
    $AllowQuery = $True

    If($UserName.length -ne 0 -and $Password.length -eq 0){
        Write-Host "Please Enter Correct User and Password"
        $AllowQuery = $False
    }
    If($UserName.length -eq 0 -and $Password.length -ne 0){
        Write-Host "Please Enter Correct User and Password"
        $AllowQuery = $False
    }
    If($UserName.length -ne 0 -and $Password.length -ne 0){
        $SP['Credential'] = Get-Credential -Credential (Create-Cred -Username $UserName -Password $Password)
        $AllowQuery = $True
    }

    If($AllowQuery){
        Try{
            Get-WmiObject @sp -ErrorAction STOP
        }
        Catch{
            $_.Exception.Message
        }
    }
}

Get-WMInformation -NameSpace root\cimv2 -Class Win32_OperatingSystem
Get-WMInformation -NameSpace root\cimv2 -Class Win32_OperatingSystem -ComputerName Server2
Get-WMInformation -NameSpace root\cimv2 -Class Win32_OperatingSystem -AuthentLvl PacketPrivacy -ComputerName Server1 -Username Admin -Password Password