Reputation: 337
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?
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
Upvotes: 2
Views: 642
Reputation: 439587
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 positive 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.
Upvotes: 4