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

PowerShell – By Reference

Background

It is always so easy to talk about things we know so little of.

Code

Outline

  1. Calling Routine
    • Each variable to pass by ref
      • Syntax
        • argument-in-called function ([ref] $local-variable)
      • Sample
        • strNew ([ref] $newCompanyName)
  2. Called Routine
    • Add Param Clause
      • Syntax
        • [ref] $variable-name
      • Example
        • [ref] $companyName
    • Explicitly state that value is being changed
      • Syntax
        • $variable.Value=[new-value]
      •  Example
        •   $strNew.Value=”Inprise Corp”

PowerShell


Set-StrictMode -Version Latest

function passByRef
{

    Param($str, [ref] $strNew, [ref] $loadDuration, [ref] $ratio)
    $str="Inprise Corp"
    $strNew.Value="Inprise Corp"
    $loadDuration.Value=100
    $ratio.Value=10

    $result = $loadDuration.Value / $ratio.Value
}

$company = "Borland"
$companyNameChange = ""
$loadDuration=0
$ratioLocal=-1

passByRef $company -strNew ([ref]$companyNameChange) -loadDuration ([ref]$loadDuration) -ratio ([ref]$ratioLocal)

"Company is $company"
"Company Name Change is $companyNameChange"
"loadDuration is $loadDuration"
"ratioLocal is $ratioLocal"

"Press Enter to complete"

#Wait
$HOST.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | OUT-NULL;
$HOST.UI.RawUI.Flushinputbuffer();

Output

passByRef_20181015_0721PM

Listening

Listening to Paul Simon..

Something so right
Link

Lyrics

When the fever runs high
You’ve got the look of love light
In your eyes
And I was in crazy motion
‘Til you calmed me down
It took a little time
But you calmed me down
When something goes wrong
I’m the first to admit it
I’m the first to admit it
But the last one to know
When something goes right
Well it’s likely to lose me
It’s apt to confuse me
It’s such an unusual sight
I can’t get used to something so right
Something so right

 

Oliver Lipkau :- Get Ini File Contents in PowerShell

Background

In a previous post ended up hard coding database connectivity information in the the actual PowerShell code.

Not a good look.

Let us move that into an INI File.

Oliver Lipkau

BTW, here is the link to the previous post :

Db/2 – PowerShell – Lab Exercises – 01
Link

Oliver Lipkau

Ini File Management

PowerShell

Outline

  1. PowerShell
    • PowerShell Function File
      • Get-IniContent.ps1
    • Powershell PSM1
      • PSIni.psm1
    • Sample Invocation
      • readIniFile.ps1

PowerShell Function File

Get-IniContent.ps1
Set-StrictMode -Version Latest
Function Get-IniContent {

<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>&lt;#

<span id="mce_SELREST_end" style="overflow:hidden;line-height:0;"></span>$FileContent["Section"]["Key"]
        -----------
        Description
        Returns the key "Key" of the section "Section" from the C:\settings.ini file  

    .Link
        Out-IniFile
#&gt;  

    [CmdletBinding()]
    Param(
        [ValidateNotNullOrEmpty()]
        [ValidateScript({(Test-Path $_) -and ( ( (Get-Item $_).Extension -eq ".ini") -or ( (Get-Item $_).Extension -eq ".txt") ) })]
        [Parameter(ValueFromPipeline=$True,Mandatory=$True)]
        [string]$FilePath
    )  

    Begin
        {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}  

    Process
    {
        Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing file: $Filepath"  

        $ini = @{}
        switch -regex -file $FilePath
        {
            "^\[(.+)\]$" # Section
            {
                $section = $matches[1]
                $ini[$section] = @{}
                $CommentCount = 0
            }
            "^(;.*)$" # Comment
            {
                if (!($section))
                {
                    $section = "No-Section"
                    $ini[$section] = @{}
                }
                $value = $matches[1]
                $CommentCount = $CommentCount + 1
                $name = "Comment" + $CommentCount
                $ini[$section][$name] = $value
            }
            "(.+?)\s*=\s*(.*)" # Key
            {
                if (!($section))
                {
                    $section = "No-Section"
                    $ini[$section] = @{}
                }
                $name,$value = $matches[1..2]
                $ini[$section][$name] = $value
            }
        }
        Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing file: $FilePath"
        Return $ini
    }  

    End
        {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
} 

PowerShell Application File

PSIni.psm1

$PsIniModuleHome = Split-Path -Path $MyInvocation.MyCommand.Path -Parent

# Name of the Section, in case the ini file had none
# Available in the scope of the module as `$script:NoSection`
$script:NoSection = "_"

# public functions
. "$PsIniModuleHome\Functions\Get-IniContent.ps1"

readIniFile.ps1

Set-StrictMode -Version Latest

###########################################################
# Import Module
###########################################################
Import-Module .\PSIni.psm1  -NoClobber -ErrorAction Stop

###########################################################
# Get Current Folder
###########################################################
$currentFolder=Convert-Path .

###########################################################
# Ini - Get Current File
###########################################################
$fileIni = "dbsettings.ini"

###########################################################
# Ini - Get Current File ( fullname)
###########################################################
$fileIniFullname = $currentFolder + [IO.Path]::DirectorySeparatorChar + $fileIni;

$fileContent = Get-IniContent ($fileIniFullname);

###########################################################
# Ini File - Read
###########################################################
$section="Database";

$key="server";
$dbServerHost = $fileContent[$section][$key]

$key="port";
$dbServerPort = $fileContent[$section][$key]

$key="database";
$dbDatabase = $fileContent[$section][$key]

$key="userid";
$dbUserID = $fileContent[$section][$key]

$key="password";
$dbUserPassword = $fileContent[$section][$key]

###########################################################
# Ini File - Display
###########################################################
"Database Server :- $dbServerHost"

"Database Server Port :- $dbServerPort"

"Database :- $dbDatabase"

"Database UserId :- $dbUserID"

"Database User Password :- $dbUserPassword"

Configuration Files

Outline

  1. Configuration Files
    • Ini File
      • dbsettings.ini

Configuration File

dbsettings.ini

[Database]
server=localhost
port=50000
database=WIDEWRLD
userid=db2user
password=simplepassword

Control Files

Outline

  1. Invoke
    • PowerShell
      • pass file name to Powershell file

Powershell

Invoke

powershell -file ./readIniFile.ps1
Output

invoke_2018104_0447PM

Dedicated

Dedicated to Oliver Lipkau :-

Work with INI files in PowerShell using hashtables
Link