WMI – Client – PowerShell & Linux

Background

Will like to provide a sample working code for invoking wmic from a Linux box.

Our scripting code will be Powershell.

 

Code

Outline

  1. Command Line Arguments
    • Targeted hostname using -hostname <target>
    • wmic authentication file using -fileAuthentication <filename>
  2. Invoke-Expression
    • Invoke Script using Invoke-Expression
    • Capture Output
  3. Parse Captured Output using Operating System ( OS ) Line Break (CR / CRLF ) as a delimiter
    • Parse Line by Line output using column delimiter in this case ( | )
      • Format column output where appropriate
        • Judging by column header

Script


[CmdletBinding()]
param( `
         [Parameter (mandatory=$true)] `
         [string] $hostname `

       , [Parameter (mandatory=$false)] ` 
         [string] $fileAuthentication = "wmi.txt" `
    )

#set strict mode
Set-StrictMode -Version Latest

#declare variables

[int] $exitCodeFileAuthenticationSpecified = 1
[int] $exitCodeFileAuthenticationExistence =2

[Boolean] $fileAuthenticationExists = $false

[string]  $log = ""

[string]  $CHAR_LINE_BREAK = [Environment]::NewLine

[string]  $FORMAT_COLUMN_DATA_DISPLAY = "`t {0}:-  {1}"

[string]  $cmdLineFormat = "{0} -A {1}  //{2} '{3}'  "

[string]  $app = $null;

[string]  $query = $null;

[int]    $GB = ( 1024 * 1024 * 1024)

[int]    $dataValue = 0;

[Boolean] $indicatorCaptureOutput = $false;

<#
   Set Variables
#>

$app = "/usr/bin/wmic"


$query = "select Size, FreeSpace from Win32_LogicalDisk"


<#
	Validate File Authentication - Specified
#>
if (
          ( $fileAuthentication -eq $null ) `
     -or ( $fileAuthentication -eq "" ) `
   )
{

    Write-Host "Please supply authentication file name using -fileAuthentication <filename>"
   
    exit $exitCodeFileAuthenticationSpecified

}

<#
	Validate File Authentication - Availability
#>
$fileAuthenticationExists = Test-Path -Path $fileAuthentication -PathType Leaf

if ($fileAuthenticationExists -eq $false)
{

    $log = "WMI Authentication File ( {0} ) does not exist" -f  $fileAuthentication

    Write-Host $log

    exit $exitCodeFileAuthenticationExistence
}


<#
	Prepare Payload
		$app => wmic
		$fileAuthentication => -A <fileAuthentication>
		$hostname => //hostname
		$query => WMI Query
#>

$cmdLine = $cmdLineFormat -f $app, $fileAuthentication, $hostname, $query

#Show Command Line Variables
Write-Host "Running this command Line $cmdLine"

#Run Command Using Invoke-Expression
#Capture Command Output in $queryOutput
$queryOutput = Invoke-Expression $cmdLine

#Show Query we ran
$log = "Results of running query {0}" -f $query

Write-Host $log

Write-Host ""

#Split output based on line endings
$queryOutputArray = $queryOutput.Split($CHAR_LINE_BREAK)

#Set Line Number
$iLineNumber = 0

#Initialize outer loop variables
$queryOutputHeaderColumnArray = $null


#Iterate Output using Line Ending
foreach($queryOutputRec in $queryOutputArray)
{

    #reset output buffer 
    $log = $null
    $queryOutputDataArray = $null
    $queryOutputDataColumnArray = @()
    $indicatorCaptureOutput = $false

    #increment line number
    $iLineNumber = $iLineNumber + 1

    #skip over CLASS INDICATOR
    #Line Number 1
    if ($iLineNumber -eq 1)
    {

        $indicatorCaptureOutput = $false
    	
    }
    # Capture Column Header
    # Line Number 2
    elseif ($iLineNumber -eq 2 )
    {

        #capture Header Row
        $queryOutputHeaderRow = $queryOutputRec

        #capture Header Column Array
        $queryOutputHeaderColumnArray = $queryOutputRec.Split("|")

        $indicatorCaptureOutput = $false
        
    }
    else
    {

        #capture entries in post line number 2
        #into queryOutputDataArray
		$queryOutputDataColumnArray = $queryOutputRec.Split("|")
      
        $indicatorCaptureOutput = $true

    }

    if ($indicatorCaptureOutput -eq $true)
    {

         #reset column number
         $iColumn = 0
      
         #Iterate columns
         foreach ($queryOutputDataCol in $queryOutputDataColumnArray )
         {

             #Based on current column get column header
             $queryOutputHeaderCol = $queryOutputHeaderColumnArray[$iColumn]
      
             if ( `
                      ( $queryOutputHeaderCol -eq "Size") `
                  -or ( $queryOutputHeaderCol -eq "FreeSpace") `
                )
             {


				$dataValue = ( [int64] ($queryOutputDataCol) ) / ( $GB );
                
                $dataValueGB = ( [Math]::Round($dataValue, 0))

                $queryOutputDataColFormatted = "{0} GB" -f $dataValueGB 

             }
             else
             {

                 $queryOutputDataColFormatted = $queryOutputDataCol;

             }

             #Prepare column data output
             $log = $FORMAT_COLUMN_DATA_DISPLAY -f `
                        $queryOutputHeaderCol `
                      , $queryOutputDataColFormatted	    
               
             #Display Output 
             Write-Host $log
         
             #increment column marker
             $iColumn = $iColumn + 1

         } # Columns

		 #Empty Lines
		 Write-Host ""

    } # Data to output
	
	
}


Invoke

Outline

  1. Invoke PowerShell file
    • Arguments
      • Targeted hostname using -hostname <target>
      • wmic authentication file using -fileAuthentication <filename>

Bash

 

</span>
<pre>
pwsh ./wmic_invoke.ps1 -hostname kb -fileAuthentication wmi.txt | more

Output

Image

 

Source Code

GitHub

Gist

DanielAdeniji/wmic_invoke.ps1
Link

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s