Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell match operator on cmdlet output OR variable name for pipeline output?

I have a simple executable that runs, returns a few lines of code.

I need to grab a section of hex out of that line and store it in a variable.

I have something that works, but would like to make it cleaner? or one line?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The output is several lines, I only care about the one with the hex code.
Typical return string

Info: Download of filename (0xff77) completed
$test1 = .\some.exe 2>&1 | Select-String -Pattern "0x"
$test1 -match "[0-9a-fA-F]{4}"
$test1 = $Matches[0]

I tried piping the output of the first line like so

$test1 = .\some.exe 2>&1 | Select-String -Pattern "0x" | -match "[0-9a-fA-F]{4}"

Obviously that didnt work, and I cant find much else on a better way to do this.

Is there a way to address the result of the previous pipeline to pass it to the match command?

$test1 = .\some.exe 2>&1 | Select-String -Pattern "0x" | $HiddenPrevPipeVar -match "[0-9a-fA-F]{4}"

What I want my $test1 to be equal to is the hex code ff77

>Solution :

Let Select-String perform the regex matching for you:

$test1 =
  (.\some.exe 2>&1 | Select-String -Pattern '(?<=0x)[0-9a-f]+').Matches.Value
  • Select-String outputs Microsoft.PowerShell.Commands.MatchInfo instances describing each match, and its .Matches property contains a collection of System.Text.RegularExpressions.Match instances describing what the regex passed to -Pattern matched. The .Value property of each such instance contains the matched text.

  • While it is possible to use capture groups ((...)) in the regex and reference what they captured via .Matches as well, in this case it is simpler to use a negative look-behind assertion ((?<=...)) in order to effectively exclude 0x from the match reported in .Value

  • Also note that Select-String, like PowerShell in general, is case-insensitive by default, so that [a-f] in the regex covers both lowercase and uppercase letters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading