Replacing escape characters in Powershell

I have a line consisting of

"some text \\computername.example.com\admin$". 

How would I make a replacement, so my final result would be just "computer_name"

My problems don't seem to know how to avoid two backslashes. To keep things simple, I would rather not use regexp :)

EDIT: It actually looks like stackoverflow is having double backslash problems, it should be a double backslash, not the one shown

+4
source share
2 answers

firstly, there is absolutely nothing wrong with the presented Regex method. However, if you are nasty, check the following:

 $test = "some text \\computername.example.com\admin$" $test.Split('\')[2].Split('.')[0] 

Very simplified testing shows that split on my machine is a little faster than it costs:

 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 
+4
source

I do not think that in this case you will be able to avoid regular expressions.

I would use this template:

 '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 want to get only computer_name from a string:

 'Some text \\computername\admin$' -replace '.*\\\\(\w+)\\(\w+)\$', '$1' 

which returns

 PS C:\> 'Some text \\computername\admin$' -replace '.*\\\\(\w+)\\(\w+)\$', '$1' computername 
+5
source

All Articles