Powershell/Regular Expression :- Get Host’s IP Address

Background

Quick follow-up to our past attempts at using Regular Expression to parse data within a lithe PowerShell Script.

Regular Expression

Positive Look Behind

  1. Regular-Expressions.Info
    • Lookahead and Lookbehind Zero-Length Assertions
      • Web Link
        Link
      • The construct for positive lookbehind is (?<=text): a pair of parentheses, with the opening parenthesis followed by a question mark, “less than” symbol, and an equals sign.
    • Regular Expression Reference: Special Groups
      • Web Link
        Link
      • Matches at a position if the pattern inside the lookbehind can be matched ending at that position.
      • Insight
        regular-expressions.info.positive.lookbehind.20190411.0825AM

Code

Powershell

Outline

  1. Get results of running IPConfig
    • Run IPConfig
    • Capture output in local variable
  2. Prepare Regular Expression
    • Look for IP Address
      • IPv4 Address Only

Regular Expression


(?<=IPv4 Address(\. )*): (\w*).(\w*).(\w*).(\w*)

Actual Code


Set-StrictMode -version 2
 
[string] $regExpPattern=$null;
[string] $inputString=$null;
[int]    $iNumberofMatches=0;
[object] $objList =$null;
[object] $objRegEx =$null;
[string] $objType = $null;
[int]    $iElementID = 0;
[string] $log=$null;
[string] $regExpOption=$null;
[Boolean] $debug = $false;
#[Boolean] $debug = $true;

[string]$domainName = $null;
[array]$domainList = $null;
[int] $domainListNumberofEntries=0;
[string]$topLevelDomain = $null;
[string]$secondLevelDomain = $null;
    
        
# Regular Expression
# Look for IPV4, once found get periods
#   look for 4 digits
# (?<=IPv4 Address(. )*): (\w*).(\w*).(\w*).(\w*)
$regExpPattern= "(?<="
$regExpPattern+= "IPv4 Address" 
$regExpPattern+= "(\. )*";
$regExpPattern+= ")";

$regExpPattern+= ":";
$regExpPattern+= " ";
$regExpPattern+= "(\w*).(\w*).(\w*).(\w*)";

# Regular Expression Option
$regExpOption="IgnoreCase";

# Run IP Config
$inputString = ipconfig

if ($debug)
{

    Write-Host;
    Write-Host;

    $log = "Input is {0} " -f $inputString;

    Write-Host($log);
   
    $log = "==========================================================================="
    Write-Host($log);

    Write-Host;
    
    
}

$log = "[regex]::expression is {0} " -f $regExpPattern;
Write-Host($log);


$objList = ( [regex]::matches( `
                                  $inputString `
                                , $regExpPattern `
                                , $regExpOption`
                             ) `
            )
 
if ($objList)
{
 
    if ($debug)
    {
         
        $objType = $objList.GetType();
 
        $log = "[regex]::matches return type is {0} " -f $objType;
 
        Write-Host($log);
 
    }
 
     
    $iNumberofMatches = $objList.Count;
    
    if ($debug)
    {   
 
        $log = "Number of Matches is {0}" -f $iNumberofMatches;
 
        Write-Host($log);
        
    }       
 
    #$objList;
    
    if ($iNumberofMatches -gt 0)
    {
 
        ForEach ($obj in $objList)
        {

            $ipAddress = $obj.Value;
        
            $log = "IP Address is {0}"  -f $ipAddress;
         
            Write-Host($log);
        
        }   
    }
 
 
}
else
{

	Write-Host "==================="
	$inputString
	Write-Host "==================="

    Write-Host "$objList is null"
}

Output

regex.regAhead.20190411.0145PM

Powershell :- Regular Expression – Using [regex]::matches

Background

In our last post spoke about using the match operator to issue Regular Expression calls.

Lineage

  1. PowerShell :- Regular Expression
    Link

RegEx Class

The -Match operator is a bit restrictive in terms of flexibility and so it is likely better to utilize the RegEx Class.

Outline

  1. Access RegEx Class Match operator
    • The first operand is the text
    • The second operator is the pattern
    • And, the third is RegEx Options
      • In our case, ignorecase
  2. Result is sent back as a collection
    • Specifically System.Text.RegularExpressions.MatchCollection
    • Simple access using index suffixes for our case

Code



Set-StrictMode -version 2

[string] $regExpPattern=$null;
[string] $fullname=$null;
[int]    $iNumberofMatches=0;
[hashtable] $obListofNames =$null;
[object] $objRegEx =$null;
[string] $listofNamesType = $null;
[int]    $iElementID = 0;
[string] $log=$null;
[string] $regExpOption=$null;
[Boolean] $debug = $false;
#[Boolean] $debug = $true;

# Regular Expression
$regExpPattern="(\w+)(\w+)";

# Regular Expression Option
$regExpOption="IgnoreCase";

$fullname="Daniel Adeniji"


$objListofNames = ( [regex]::matches( `
                                          $fullname `
                                        , $regExpPattern `
                                        , $regExpOption`
                                        ) `
                  )

if ($objListofNames)
{

    if ($debug)
    {

        
        $log = "[regex]::expression is {0} " -f $regExpPattern;

        Write-Host($log);

        
        $listofNamesType = $objListofNames.GetType();

        $log = "[regex]::matches return type is {0} " -f $listofNamesType;

        Write-Host($log);

    }

    
    $iNumberofMatches = $objListofNames.Count;

    $log = "Number of Matches is {0}" -f $iNumberofMatches;

    Write-Host($log);

    if ($iNumberofMatches -gt 0)
    {

        $log = "First name is {0}" -f $objListofNames[0];

        Write-Host($log);

    }

    if ($iNumberofMatches -gt 1)
    {

        $log = "Last name is {0}" -f $objListofNames[1];

        Write-Host($log);

    }   

}
else
{
    Write-Host "$objListofNames is null"
}

Output

regex.matches.output.20190406.0935AM

References

  1. Microsoft
    • System.Text.RegularExpressions
      • Regex.Matches Method

PowerShell :- Regular Expression

 

Background

Looking at a useful tool written in PowerShell.

But, it was fading.

Time to play around with Regular Expression, Regex.

Code

Powershell

Objective

  1. Prepare Regular Expression
    • In our case, stored in $regexp
  2. Prepare Input
    • In our case, store in $fullname
  3. Issue RegEx call using -match operator
  4. Results is saved in Hashtable
    • The name of the system populated Hashtable is $hashtable
      • The 0th element is the passed in input
      • 1 is the first match
      • 2 is the second match
      • And, on and on

Implementation


Set-StrictMode -version 2

[string] $regexp=$null;
[string] $fullname=$null;
[int]    $iNumberofMatches=0;
[hashtable] $obListofNames =$null;

$regexp="(\w+) (\w+)";
$fullname="Daniel Adeniji"

$fullname -match $regexp  | Out-Null;

$obListofNames = $Matches;

$iNumberofMatches = $obListofNames.Count-1;

Write-Host("Number of matches :- " + $iNumberofMatches);

if ($obListofNames)
{
    Write-Host("Full Name :- " + $obListofNames[0]);
}

if ($iNumberofMatches -gt 0)
{
    Write-Host("First Name :- " + $obListofNames[1]);
}

if ($iNumberofMatches -gt 1)
{
    Write-Host("Last Name :- " + $Matches[2]);
}

Output

powershell.regex.20190405.0348PM

XPath code Generator – Web Tools

Background

Wanted to quickly review freely available online tools for generating Xpath from XML documents.

Sample XML Documents

Will use these XML documents as samples :-

  1. Microsoft
    • Docs. / NET / C# Guide / Programming guide / Programming concepts / LINQ
      • Sample XML File: Customers and Orders in a Namespace
        Link

 

Tools

  1. Xmltoolbox
    • XPath Generator
  2. Qutoric
  3. XPather.com

 

In depth

Xmltoolbox

XPath Generator

Author

Xmltoolbox is authored by Ole Bille.

Usage

Outline
  1. Launch web browser
  2. And, go here ( http://xmltoolbox.appspot.com/xpath_generator.html )
  3. Paste the XML text into the canvas
  4. In the loaded canvas, click on the elements you want evaluated
  5. Please review and capture the generated Xpath results

 

Screenshots

xpathgenerator.20181217.0344AM

qutoric

PathEnq

Usage

Outline
  1. Launch web browser
  2. And, go here ( http://www.qutoric.com/xslt/analyser/xpathtool.html )
  3. Invoke the Choose File button at the bottom of the screen
  4. Select the file to be evaluated
  5. In the loaded canvas, click on the elements you want evaluated

 

Screen Shots

xmlSource.20181217.0319AM

xmlSource.20181217.0322AM

 

XPather.com

Author’s Guideline

  1. This web app enables you to query XML/HTML documents with your browser in real time. It can generate queries for you too!
    • You can enter your xpath query in the top-left panel and it will be instantly executed against this document.
    • To generate an xpath query for a specific element, please hold CTRL and hover over it. An xpath is generated.

Usage

To generate an XPath, please paste the XML into the canvas.

Once the XML is available and accessible, please move your cursor to the screen area, hold down the Ctrl button while hovering or selecting the XML tag or body.

Samples

Sample #1

xpather.com.20181217.0308AM

Deficiency

  1. Supports Element, but not attribute

 

 

 

 

 

.Net Frameworks – Installed Products

Background

Wanted to get a list of Microsoft .Net Frameworks installed on a machine.

Windows Management Interface ( WMI )

Introduction

In this post, we will use Windows Management Interface, WMI.

 

Powershell

Outline

  1. Get-WmiObject
    • Class :- Win32_Product
    • Filter :- Microsoft .Net Framework
    • Columns :-
      • Name
      • Version

Code


[char] $CHAR_WILDCARD="*"

$computer=$env:computername

$filter="Microsoft .Net Framework"

$filterWildcard= $filter + $CHAR_WILDCARD

Get-WmiObject -Class Win32_Product -Computer $computer | `

	Select @{"Name"="Name"; "Expression"={($_.Name.trim())}}, Version | `

	Where-Object -FilterScript {$_.Name -like $filterWildcard} | `

	Sort-Object Name, Version -Descending

Images

getVersionNumber_self_20181207_1209PM

Powershell

Outline

  1. Get-WmiObject
    • Class :- Win32_Product
    • Filter :- Microsoft .Net Framework
    • Columns :-
      • Name
      • Version

Code


set "_wildcard=%%"

wmic product where "Name like 'Microsoft .Net %_wildcard%' " get Name, Version

Images

MSWindowsBatch.20181207.1229PM

Win OS RecycleBin – Access via Powershell

Background

Over the Thanksgiving weekend spent time tackling a couple of machines that were running low on storage.

There are so many ways that one can lose space in MS Windows.

And, so we look between the white spaces.

in the past

  1. Recycle Bin Emptying Using Powershell
    Link

Recycle Bin

For those who want to programmatically look and repair, here is a bit of code to look in the Recycle Bin.

Code


Set-StrictMode -Version 2

$userRecycleBin_ID = 0x0a

Function Get-RecycleBin
{

	# Instanciate Shell Application
  	$objShell = New-Object -ComObject Shell.Application;

	#Get Recycle Bin
	$objShellRecycleBin = $objShell.NameSpace($userRecycleBin_ID)

	#Get Recycle Bin Items
	$objItems = $objShellRecycleBin.Items();

	#Get Recycle Bin Items
	#Only interested in explicitly listed attributes
	#$objItems | Select-Object * | Out-GridView -Wait
	$objItems | Select-Object Path, Name, IsFolder, Type, Size | Out-GridView -Wait

	return ( $objItems );

}

Function Stat-RecycleBin
{
	$objShell = New-Object -ComObject Shell.Application;

	$objItems = $objShell.NameSpace($userRecycleBin_ID).Items();

	#| measure
	$lNumberofEntries = $objItems.Count

	return ( $lNumberofEntries);

}

$objItems = Get-RecycleBin

$lNumberofEntries = $objItems.Count

$log = "Number of entries in reccyle bin {0}" -f $lNumberofEntries

Write-Host $log

Invoke


powershell  -noprofile -executionpolicy bypass -file ./recycleBinBrowse.ps1

Dedicated

As always most of this is somebody else.

He wrote it in two lines.

There were things I was missing and so I had to break it into single statements.

If you find find yourself having to do so same, don’t feel bad nor lonesome for the handicap.

 

Referenced Work

  1. Windows Dev Center
    • Docs > WindowsDesktop > The Windows Shell > Shell Reference > Shell Objects for Scripting and Microsoft Visual Basic > Shell > NameSpace
      • Shell.NameSpace method
        Link
    • Docs / Windows / Desktop / API / The Windows Shell / Shldisp.h / ShellSpecialFolderConstants enumeration
      • ShellSpecialFolderConstants Enumeration
        Link

Recycle Bin Emptying Using Powershell

Background

One might find that the Recycle Bin is taking up a good chuck of storage.

Remediation

Powershell

Let us use Powershell to dump our recycle bins.

Cmdlet :- Clear-RecycleBin

Syntax

Here is the Syntax

Clear-RecycleBin-Syntax

Sample

All Drives
Script
Clear-RecycleBin  -Force
Output

force.20181124.1008AM.PNG

Drive Letters Specified
Script
Clear-RecycleBin  -DriveLetter "C", "D","E"
Output

foldersSpecified.20181124.0950AM.PNG

Confirm
Confirm – True
Script
Clear-RecycleBin  -Confirm:$true
Output

confirmTrue.20181124.0955AM

Explanation
  1. Prompted
Confirm – False
Script
Clear-RecycleBin  -Confirm:$false
Output

confirmFalse.20181124.0957AM.PNG

Explanation
  1. Not Prompted

Errors

Error :- Clear-RecycleBin : The system cannot find the file specified
Sample

Clear-RecycleBin -Confirm:$false -DriveLetter "C", "D","E"

Output – Image

error.cannotFindtheFileSpecified.20181124.1030AM

Output – Textual

Clear-RecycleBin : The system cannot find the file specified
At line:1 char:1
+ Clear-RecycleBin -Confirm:$false -DriveLetter "C", "D","E"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (RecycleBin:String) [Clear-RecycleBin], Win32Exception
+ FullyQualifiedErrorId : FailedToClearRecycleBin,Microsoft.PowerShell.Commands.ClearRecycleBinCommand

Overlook

Try to use “-ErrorAction SilentlyContinue


Clear-RecycleBin -Confirm:$false -DriveLetter "C", "D","E"  -ErrorAction SilentlyContinue

Dedicated

Dedicated to Gee Law

Gee Law

Blog Posts & Git Hub Issues

  1. GeeLaw.blog
    • PowerShell codebase misuses SHEmptyRecycleBin function in Clear-RecycleBin cmdlet
      Link
  2. GitHub
    • PowerShell
      • Misuse of `SHEmptyRecycleBin` in `Clear-RecycleBin` cmdlet #6743Link

Sidenotes

Link
Sidenote
 I wish Raymond Chen could write a blog entry on SHEmptyRecycleBin if there’s something interesting to add. He’s an expert of Windows shell programming. However, his suggestion box is currently closed and there’s no prescribed way to make a suggestion (though I could have sent him an email, but that would be too impolite), so I can only make wishes.