Powershell – String Splitting Using The Split Operator

Background

Recently I had to parse some contents using Powershell.

It was an ugly struggle for me.

Code


Set-StrictMode -Version 1.0

$listofNames = "John Smith;; Paul Young;; Martin Short;; Sarah Bishop;;";

function parseName([string]$data)
{

    [string] $separator = "";

    [System.StringSplitOptions]$options = [System.StringSplitOptions]::RemoveEmptyEntries;

    [string] $matchingOption = "";
    [int] $maxNumberofMatches =0;

    [int] $id=0;

    [string]$name = "";

    [string]$nameFormatted = "";

    $separator = ";;";
    $matchingOption = "RegexMatch,IgnorePatternWhitespace";

    $id = 0;

    Write-Output "Data is $data"
    Write-Output ""

    Write-Output "Separator is $separator"
    Write-Output ""

    #$list = $data -split $separator, 0, "SimpleMatch"; 

    $list = $data -split `
                  $separator `
                , $maxNumberofMatches `
                , $matchingOption;

    $log = "Number of entries in list is {0}" -f $list.count;

    Write-Output $log

    Write-Output ""

    foreach ($name in $list)
    {

        if ($name)
        {

            $id = $id +1;

            $nameFormatted = $name.trim();

            $log = "{0}) {1}" -f $id, $nameFormatted;

            Write-Output $log

        }

    }

    Write-Output ""
    Write-Output ""

    $log = "Number of names processed is {0}" -f $id;

    Write-Output $log

    Write-Output ""

}

parseName ($listofNames);

Code Sharing

GitHub

Gist

DanielAdeniji/PowershellOperatorSplit.ps1
Link

 

References

  1. Microsoft
    • Powershell

 

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