Powershell – Split text to 2 parts

Example how to split text into 2 part with Powershell version 2+.

Example 1:

#Simple text split based on delimiter
$text = "Left Part;Right Part"
$pos = $text.IndexOf(";")
$leftPart = $text.Substring(0, $pos)
$rightPart = $text.Substring($pos+1)
Write-Output $leftPart
Write-Output $rightPart

Example 2:

#Set own delimiter in text and split then
$text = "Left Part - Right Part" -replace " - ",";"
$pos = $text.IndexOf(";")
$leftPart = $text.Substring(0, $pos)
$rightPart = $text.Substring($pos+1)
Write-Output $leftPart
Write-Output $rightPart

Example 3:

#Comprehensive example - load values from array, set own delimiter, split them into left and right part, save them as object values and export object.
$text = (
         "Left Part1 - Right Part1",
         "Left Part2 - Right Part2",
         "Left Part3 - Right Part3",
         "Left Part4 - Right Part4"
        )
$ObjArr = @()

foreach ($item in $text) {

    $obj = New-Object psobject

    [array]$ReplacedText = $item -replace " - ",";"
    [int]$LineArrCounter = 0
    $pos = $ReplacedText[$LineArrCounter].IndexOf(";")
    $leftPart = $ReplacedText[$LineArrCounter].Substring($LineArrCounter, $pos)
    $rightPart = $ReplacedText[$LineArrCounter].Substring($pos+1)
    $LineArrCounter++

    $obj | Add-Member -MemberType NoteProperty -Name LeftPart -Value $leftPart
    $obj | Add-Member -MemberType NoteProperty -Name RightPart -Value $rightPart

    $ObjArr += $obj
}
Write-Output $ObjArr

Source

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.