Replacing escape characters in Powershell
Solution 1
first, there is absolutely nothing wrong with the Regex method that is presented. However, if you are deadset against it, Check this:
$test = "some text \\computername.example.com\admin$"
$test.Split('\')[2].Split('.')[0]
Very simplistic testing shows that the split is marginally faster on my machine for what it is worth:
12:35:24 |(19)|C:\ PS>Measure-Command {1..10000 | %{'some text \\computername.example.com\admin$'.Split('\')[2].Split('.')[0]}}
Days : 0
Hours : 0
Minutes : 0
Seconds : 1
Milliseconds : 215
Ticks : 12159984
TotalDays : 1.40740555555556E-05
TotalHours : 0.000337777333333333
TotalMinutes : 0.02026664
TotalSeconds : 1.2159984
TotalMilliseconds : 1215.9984
12:35:34 |(20)|C:\ PS>Measure-Command {1..10000 | %{'Some text \\computername\admin$' -replace '\\\\(\w+)\\(\w+)\$', '$1'}}
Days : 0
Hours : 0
Minutes : 0
Seconds : 2
Milliseconds : 335
Ticks : 23351277
TotalDays : 2.70269409722222E-05
TotalHours : 0.000648646583333333
TotalMinutes : 0.038918795
TotalSeconds : 2.3351277
TotalMilliseconds : 2335.1277
Solution 2
I don't think you're going to get away from regular expressions in this case.
I would use this pattern:
'Some text \\computername\admin$' -replace '\\\\(\w+)\\(\w+)\$', '$1'
which gives you
PS C:\> 'Some text \\computername\admin$' -replace '\\\\(\w+)\\(\w+)\$', '$1'
Some text computername
or if you wanted only the computername from the line:
'Some text \\computername\admin$' -replace '.*\\\\(\w+)\\(\w+)\$', '$1'
which returns
PS C:\> 'Some text \\computername\admin$' -replace '.*\\\\(\w+)\\(\w+)\$', '$1'
computername
fenster
Updated on June 23, 2022Comments
-
fenster almost 2 years
I have a string that consists of
"some text \\computername.example.com\admin$".
How would I do a replace so my final result would be just "computername"
My problems appears to not knowing how to escape two backslashes. To keep things simple I would prefer not to use regexp :)
EDIT: Actually looks like stackoverflow is having problems with the double backslash as well, it should be a double backslash, not the single shown
-
JasonMArcher about 15 yearsAnd if there could be additional text after that drive path, you can add '.*$' (ignore my quotes) to the end of that regular expression.
-
fenster about 15 yearsThanks EBGreen. Both worked fine, but chose your answer because it introduced me to a new element of split I had not thought of, then again I should really take the time to learn more about regex.