选择不在powershell中使用变量的字符串
我已将MAC地址作为字符串存储在变量中:选择不在powershell中使用变量的字符串,powershell,syntax,powershell-2.0,powershell-3.0,Powershell,Syntax,Powershell 2.0,Powershell 3.0,我已将MAC地址作为字符串存储在变量中: $macaddress= "1234567" $testing = { arp -a; | select-string $macaddress } Write-Host $testing 我正在尝试将命令的输出存储在另一个变量中: $macaddress= "1234567" $testing = { arp -a; | select-string $macaddress } Write-Host $testing 如果该命令在Pow
$macaddress= "1234567"
$testing = { arp -a; | select-string $macaddress }
Write-Host $testing
我正在尝试将命令的输出存储在另一个变量中:
$macaddress= "1234567"
$testing = { arp -a; | select-string $macaddress }
Write-Host $testing
如果该命令在PowerShell中执行,我看不到$macaddress
的值。它在屏幕中显示为“$macaddress”,而不是其值“1234567”
请帮助我正确设置$macaddress
的值。问题不在于如何定义变量$macaddress
,而在于如何尝试捕获命令输出。移除封装的
{…}
和代码>:
$testing = arp -a | select-string $macaddress
至于你所尝试的:
{…}
创建一个脚本块,它是一段源代码(粗略地说)供以后执行(例如,使用操作符
或&
)
如果您将脚本块传递给写入主机
-,顺便说一句,它将转换为字符串,字符串表示是{
和}
之间的脚本块的文字内容-这就是您在输出中看到$macaddress
出现(未展开)的原因
代码>终止一个命令,并且仅当您在一行上放置多个命令时才需要此命令。
管道仍然被视为单个命令,即使它由多个子命令组成;不要试图使用代码>在管道中-您将中断它(事实上,甚至您的脚本块创建命令也会中断)。请尝试以下方法:
$macAddress = "00-01-02-03-04"
arp -a | Select-String $macAddress
如果要提取与MAC地址相关的IP地址,可以执行以下操作:
$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 }