sqone2
sqone2

Reputation: 31

Capture specific text from output into a variable

I'm trying to write a script that will detect what COM port a device is plugged into, then map it to a new port.

Here is the output from the "change port" command:

PS C:\> change port
COM11 = \Device\19H2KP0
COM2 = \Device\Serial1
COM5 = \Device\Serial2
KEYSPAN#*USA19HMAP#00_00#{4d36e978-e325-11ce-bfc1-08002be10318} = \Device\ComUs19H-00
KEYSPAN#*USA19HMAP#00_00#{86e0d1e0-8089-11d0-9ce4-08003e301f73} = \Device\ComUs19H-00
USA19HP0 = \Device\19H2KP0

I need to capture the COM number prior to "\Device\19H2KP0". So in this example output, I would capture COM11 into a variable.

Next I need to run the "change port" command with that variable. i.e.:

change port COM1=$CapturedText

Thank you in advance for any assistance!

Upvotes: 0

Views: 323

Answers (2)

mjolinor
mjolinor

Reputation: 68243

Longer, but perhaps more intuitive, you can also use chained -match and -replace operators with simpler regexes:

$CapturedText = (change port) -match 'COM.+19h2kp0' -replace '^(COM\d+).+','$1'
$CapturedText

Upvotes: 0

user189198
user189198

Reputation:

Do you already know what the 19H2KP0 bit will be? If so, you could use a regular expression to detect the unique ID using a look-ahead.

Here's a fully working example, using your example text:

$Output = @"
COM11 = \Device\19H2KP0
COM2 = \Device\Serial1
COM5 = \Device\Serial2
KEYSPAN#*USA19HMAP#00_00#{4d36e978-e325-11ce-bfc1-08002be10318} = \Device\ComUs19H-00
KEYSPAN#*USA19HMAP#00_00#{86e0d1e0-8089-11d0-9ce4-08003e301f73} = \Device\ComUs19H-00
USA19HP0 = \Device\19H2KP0
"@

$Output -match "COM[0-9]{1,2}(?=.*$Id)";

Write-Host -Object ('COM port is: {0}' -f $matches[0]);

And now here is the example, using the in-line command:

$Id = '19H2KP0';
$Output = change port;
$Output -match "COM[0-9]{1,2}(?=.*$Id)";
Write-Host -Object ('COM port is: {0}' -f $matches[0]);

Result

COM port is: COM11

Upvotes: 1

Related Questions