louis
louis

Reputation: 635

select-string not taking variable in powershell

I have stored a MAC address as a string in a variable:

$macaddress= "1234567"

I'm trying to store the output from a command in another variable:

 $testing = { arp -a; | select-string  $macaddress }
 Write-Host $testing

If the command is executed in PowerShell, I do not see the value of $macaddress. It displays as a '$macaddress' in the screen instead of its value "1234567".

Please help me set the value of $macaddress correctly.

Upvotes: 3

Views: 2453

Answers (2)

mklement0
mklement0

Reputation: 440347

The problem is not how you define variable $macaddress, but in how you try to capture command output.
Remove the enclosing { ... } and the ;:

$testing = arp -a | select-string $macaddress

As for what you tried:

{ ... } creates a script block, which is a piece of source code (loosely speaking) for later execution (e.g., with operators . or &).

If you pass a script block to Write-Host - whose use you should generally avoid, by the way - it is converted to a string, and the string representation is the literal contents of the script block between { and } - that's why you saw $macaddress appear (unexpanded) in your output.

; terminates a command, and it is only necessary if you place multiple commands on a single line.
A pipeline is still considered a single command, even though it is composed of multiple sub-commands; do not attempt to use ; in a pipeline - you'll break it (and, in fact, even your script-block-creating command would break).

Upvotes: 1

Bill_Stewart
Bill_Stewart

Reputation: 24585

Try it this way:

$macAddress = "00-01-02-03-04"
arp -a | Select-String $macAddress

If you want to extract the IP address related to the MAC address, you can do this:

$macAddress = "00-01-02-03-04"
arp -a | Select-String ('\W*((?:[0-9]{1,3}\.){3}(?:[0-9]{1,3}))\W+(' +
  $macAddress + ')') | ForEach-Object { $_.Matches[0].Groups[1].Value }

Upvotes: 0

Related Questions