I’m using PowerShell 7.4.5.
First example: 'a.b' -split '.'
does not give you a two-element array of a
and b
, but a four-element array of empty strings.
Another example is 'rodtipsqleastus2.database.windows.net'.TrimStart('rodtipsqleastus2.')
. It doesn’t give you database.windows.net
but base.windows.net
instead.
Could someone throw some light here? Thanks.
3
Regarding your first issue:
PowerShell’s split
uses regular expression matching by default, cf. about_Split
RegexMatch: Use regular expression matching to evaluate the delimiter. This is the default behavior.
Use
'a.b' -split '.', 0, 'simplematch'
Note the additional , 0
as
You can use options, such as SimpleMatch, only when the Max-substrings value is specified.
Regarding your second issue:
Assuming this uses .NET’s TrimStart
, this one takes an array of characters, not a 1:1 string, cf. TrimStart(Char[]).
That means
TrimStart('rodtipsqleastus2.')
will remove all subsequent “r”s, “o”s, “d”s, “t”s and so on until it finds the first character not in that list. Which in your case is the “b”.
Not sure what would be the best solution, maybe
'rodtipsqleastus2.database.windows.net'.Substring(17)
does the trick for you.
As Marvin already pointed out, -split
is a regex operator, and .
means “any character” in the context of regex.
You can use the String.Split()
method to split on an exact substring:
$a,$b = 'a.b'.Split('.')
String.TrimStart(<characters>)
will keep trimming the start of the string as long as any of the characters passed to it matches the leading character.
To remove a specific substring at offset 0, you can use the -replace
regex operator:
$leadingString = 'rodtipsqleastus2.'
$pattern = '^{0}' -f [regex]::Escape($leadingString)
$domainWithoutLeadingLabel = 'rodtipsqleastus2.database.windows.net' -replace $pattern
The [regex]::Escape
method will correctly escape the .
in $leadingString
, and the ^
inserted in front of it ensure the regex engine only matches at the start of the input string.
If the leading string is not found, the -replace
operator will simply not do anything and instead return the original string unaltered:
PS ~> 'rodtipsqleastus2.database.windows.net' -replace $pattern
database.windows.net
PS ~> 'somethingelse.database.windows.net' -replace $pattern
somethingelse.database.windows.net
And if you’re unsure if a character is or is not a regex special token then you can regex escape the character by the following
[regex]::Escape('.')