Thursday, September 26, 2019

Split a string based on a delimiter character, only if the character is not inside of a set of quotes in Powershell

Below is the function and example. You can also strip the code out of the function and run it inline if you assign values to the 2 variables of $lineToSplit  and $splittingCharacter . $string.Split("$char") works great if there are no quotes where a character needs to be preserved. An example of where this would be useful would be

$lineToSplit = 'home, work, "last, first", mobile, address'; Obviously you don't want to split where the comma is inside of quotes.


$valueSplit = splitOutsideOfQuotes -lineToSplit $valueSplit -splittingCharacter ",";
function splitOutsideOfQuotes
{
[CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true, Position=0)]
        [string]$lineToSplit,
        [Parameter(Mandatory=$true, Position=1)]
        [string]$splittingCharacter
    )
#Region Initialization
$charArray = $lineToSplit.ToCharArray();
$stringTemp = "";
[bool] $quoteBlockerFound = $false
$returnSplitArray = New-Object System.Collections.ArrayList;
[int] $index = 0;
[int] $charCount = $charArray.Count;
#EndRegion /Initialization
foreach ($char in $charArray)
{
$index++;
if ($char -ne $splittingCharacter)
{
if ($char -ne " ") # not equal a space
{
if ($char -ne "`"") # not equal a quote
{
$stringTemp += $char;
}
elseif (($char -eq "`"") -and ($quoteBlockerFound -eq $true)) # equals a quote
{
$quoteBlockerFound = $false;
}
else
{
$quoteBlockerFound = $true;
}
}
elseif (($char -eq " ") -and ($quoteBlockerFound -eq $true))
{
$stringTemp += $char;
}
}
elseif (($char -eq $splittingCharacter) -and ($quoteBlockerFound -eq $true))
{
$stringTemp += $char;
}
else
{
$returnSplitArray.Add($stringTemp) | Out-Null;
$stringTemp = "";
}
if ($index -eq $charCount)
{
$returnSplitArray.Add($stringTemp) | Out-Null;
$stringTemp = "";
}
}
return $returnSplitArray;
}