I worked recently on some Active Directory properties and needed to split a path.
$h = ( Get-ADUser UserName -Properties HomeDirectory ).HomeDirectory $h = '\\servername\homepath.username$'
The HomeDirectory is a System.String and my variable $h contains something like \\servername\homepath.username$ (there’s a dollar at the end to hide the share).
I’d like to split on the \ character and to do so, you need to escape it with another backslash character because it’s a special character for regular expressions.
The official documentation About Split says that the delimiter is evaluated as a regular expression if I use the highlighted 3rd syntax:
The Options parameter is optional in the syntax and defaults to the value RegexMatch
The doc says:
RegexMatch: Use regular expression matching to evaluate the delimiter.
If I use the split operator like this:
$h -split '\\' $h -split '\\' | measure [string]::Empty -eq ($h -split '\\') [string]::Empty -eq ($h -split '\\') [string]::Empty -eq ($h -split '\\') [string]::Empty -eq ($h -split '\\')
I get 4 results. The first 2 results of the split operation are an empty system.string.
This is expected.
I want to capture the server name and the share name, not the backslashes and not the empty strings.
My first solution followed the idea “just ignore and discard empty strings”:
$server=$share=$null # capture $null,$null,$server,$share=$h -split '\\' # display result $server $share
My second solution is based on the idea that “there’s probably a better way to skip these empty strings”:
$server=$share=$null $server,$share=$h.Split('\\',2,'RemoveEmptyEntries') # display result $server $share
If you’ve another great idea and want to share another (better?) way to skin the cat, please post it in the comments 🙂 .