I am appearrently too stupid to do RegEx in Powershell - help!

oynaz

Platinum Member
May 14, 2003
2,449
3
81
Hi guys,

This should be a really simple problem. In my script, I need to extract a servername from a string.

String goes like

\\SERVERNAME\Sharename\Directory\Directory\

I think Regex is the easiest way to do this, but I cannot figure out how to do it.

I have tried:

Code:
$FullString = '\\SERVERNAME\Sharename\Directory\Directory\'
$ServerString = $FullString -match "\\\?\\"
and
Code:
$FullString = '\\SERVERNAME\Sharename\Directory\Directory\'
$ServerString = $FullString -replace "\\\?\\" ""

But this did not work, and both my Google-Fu and my brain seems defective right now.
Help!

By the way, I can also get this string as an object from an XML file, if it is easier to use Regex on an object.
 

Caphel

Junior Member
Jan 16, 2009
1
0
0
It looks like the regex is the problem. Try something like this:

(?<=\\{2}).*?(?=\\)
 

oynaz

Platinum Member
May 14, 2003
2,449
3
81
It looks like the regex is the problem. Try something like this:

(?<=\\{2}).*?(?=\\)

Thanks for your help, and sorry about the long reply. I went on vacation :)

Your, regex is correct I believe, and I have managed to get it to do the exact opposite of what I wanted ;-)

Code:
$FullString = '\\SERVERNAME\Sharename\Directory\Directory\'
$ServerString = $FullString -replace "(?<=\\{2}).*?(?=\\)", ""

This removes the servername from the string, returning

\\\Sharename\Directory\Directory\

I cannot figure out how to do it the other way 'round.

-match returns a boolean, right. Is there another operator I should use?
 

oynaz

Platinum Member
May 14, 2003
2,449
3
81
Hmm, I might able to use the split-path cmdlet instead of regex. If it was a file path instead of an UNC path, I could simply go:

Code:
split-path $fullstring -qualifier

However, this does not work with UNc paths. Does anyone know of an UNC version of -qualifier? I cannot find it with get-help.