I\'m trying to spit the string with a delimiter, which is a string:
$string = \"5637144576, messag<>est<<>>5637145326, 1<<>>563
EDIT 2020-05-23: I've moved my code to GitHub, here, where I've made updates to cover a few edge cases: https://github.com/franklesniak/PowerShell_Resources/blob/master/Split-StringOnLiteralString.ps1
You can use the -split operator, but it expects RegEx. Furthermore, the -split operator is only available on Windows PowerShell v3+, so we need a different method if you want something that is universally compatible with all versions of PowerShell.
A [regex] object has a Split() method that can handle this as well, but again, it expects RegEx as the "splitter". To get around this, we can use a second [regex] object and call the Escape() method to convert our literal string "splitter" into escaped RegEx.
Wrapping all this up into an easy to use function that works back to PowerShell v1 and also works on PowerShell Core 6.x.
function Split-StringOnLiteralString
{
trap
{
Write-Error "An error occurred using the Split-StringOnLiteralString function. This was most likely caused by the arguments supplied not being strings"
}
if ($args.Length -ne 2) `
{
Write-Error "Split-StringOnLiteralString was called without supplying two arguments. The first argument should be the string to be split, and the second should be the string or character on which to split the string."
} `
else `
{
if (($args[0]).GetType().Name -ne "String") `
{
Write-Warning "The first argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
$strToSplit = [string]$args[0]
} `
else `
{
$strToSplit = $args[0]
}
if ((($args[1]).GetType().Name -ne "String") -and (($args[1]).GetType().Name -ne "Char")) `
{
Write-Warning "The second argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
$strSplitter = [string]$args[1]
} `
elseif (($args[1]).GetType().Name -eq "Char") `
{
$strSplitter = [string]$args[1]
} `
else `
{
$strSplitter = $args[1]
}
$strSplitterInRegEx = [regex]::Escape($strSplitter)
[regex]::Split($strToSplit, $strSplitterInRegEx)
}
}
Now, using the earlier example:
PS C:\Users\username> Split-StringOnLiteralString "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0" "<<>>"
5637144576, messag<>est
5637145326, 1
5637145328, 0
Volla!