3

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.

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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 }

1 Comment

What are the outer brackets of select-string for? You did select-string ('('+$var+'regex'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.