Author Posts

April 10, 2014 at 7:36 pm

Location :
Name : slave-pos (redirected 2)
PrinterState : 0
PrinterStatus : 3
ShareName :
SystemName : NWTL-XCHANGE1

Hi I have this text output. I want to use powershell to get only "slave-pos(redirected 2)" How can I do this in Powershell. I am new to ti.

Operating System: Windows 2008 r2 x64

April 10, 2014 at 8:03 pm

Is that actually a string, or is that list output of a PowerShell object? If it's an object, you'd just do $object.Name . Assuming that this is text in a single string variable (not an array), then this should work:

$text = @'
Location :
Name : slave-pos (redirected 2)
PrinterState : 0
PrinterStatus : 3
ShareName :
SystemName : NWTL-XCHANGE1

$name = ''

if ($text -match '(?m)^\s*Name\s*:\s*(.+?)\s*$')
    $name = $matches[1]


April 11, 2014 at 2:30 pm


If you love to hate regex 🙂 (sorry Dave), this also works:

$name = $text -split [environment]::NewLine | foreach { if($_.startswith("Name")){$_.split(":")[1]} }


$name = $text -split "`n" | foreach { if($_.startswith("Name")){$_.split(":")[1]} }

April 11, 2014 at 6:35 pm

I can't help it. I learned regular expressions at a formative age, and now they're like my coding security blanket. 😛

May 1, 2014 at 12:05 pm

Dave can you explain in plain text the regex above?

May 1, 2014 at 7:56 pm

No problem:


  • (?m) : This sets the pattern to "multiline mode", which means that the ^ an $ anchors will match the beginning and ending of each line, respectively, instead of only the beginning and ending of the entire string.
  • ^ : This matches the beginning of any line (in multiline mode.)
  • \s*Name\s*:\s* : This matches zero or more whitespace characters followed by the word Name, followed again by zero or more whitespace characters, a colon, and zero or more whitespace characters again. This would match "Name:", " Name : ", etc, so long as no other non-whitespace was found before Name at the beginning of the line.
  • (.+?) : The parentheses are a capturing group. Whatever text is eventually matched by the regex pattern inside them can be accessed later, in this case by checking $matches[1]. The ".+" part matches one or more characters, and the "?" makes the + operator lazy (meaning it will match as few characters as possible.) I made the operator lazy because I didn't want the "." wildcard to match...
  • \s*$ : Any trailing whitespace before the end of the line.

May 1, 2014 at 11:58 pm

Thanks Dave. Very nice class about Regex. Soon as I wrote my post, I found this page

and I could follow your class much better.

Thanks a lot.
I also want to thanks Vern Anderson for his redirection.