Оператор -split ожидает RegEx, но его можно заставить сделать это хорошо.Однако оператор -split доступен только в Windows PowerShell v3 +, поэтому он не соответствует требованиям, указанным в вопросе.
Объект [regex] имеет метод Split (), который также может справиться с этим, ноон ожидает RegEx как «сплиттер».Чтобы обойти это, мы можем использовать второй объект [regex] и вызвать метод Escape () для преобразования нашей буквенной строки «splitter» в экранированный RegEx.
Оборачивая все это в простую в использовании функцию, котораяработает обратно в PowerShell v1, а также в PowerShell Core v6.
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)
}
}
Теперь, используя предыдущий пример:
PS C:\Users\username> Split-StringOnLiteralString "One two three keyword four five" "keyword"
One two three
four five
Volla!