【问题标题】:MAC address string comparison failsMAC 地址字符串比较失败
【发布时间】:2018-01-29 17:17:44
【问题描述】:

我尝试使用字符串与本地计算机的 MAC 地址进行比较,从 txt 文件 $pcliste 中提取计算机名。文本文件包含:

超级电脑 00:15:5D:FF:0B:33 av-client4 00:15:5D:FF:0B:38 温度 00:15:5D:FF:0B:39

我使用以下 PowerShell 代码:

$macadresse = Get-WmiObject Win32_NetworkAdapterConfiguration | select macaddress
$macadresse = $macadresse.macaddress

$pcnamen = Get-Content -Path $pcliste
$computername = "TEMP-NAME"

for ($i=0; $i -lt $pcnamen.Length; $i++) {
    $string =  $pcnamen[$i]
    if ($string -match $macadresse) {
        write "MAC found!"
        $index = $pcnamen[$i].IndexOf(" ")
        $computername = $pcnamen[$i].substring(0, $index)
    }
}

我的测试VM的MAC地址是00:15:5D:FF:0B:38,但循环中的字符串比较仍然是假的。

为了测试,我已经将 MAC 放入一个字符串变量中,而不是使用 Get-WmiObject 提取它,这很有效。 我还尝试使用 [string]$macadress 将提取的 macadress 转换为字符串。

我认为是某种数据类型/对象类型问题导致-match 失败。

【问题讨论】:

  • $macadresse 可能是一个数组。所以你可能需要使用-in / -contains 而不是-match 或者遍历数组。
  • 由于您显然正在读取带有主机名和 MAC 地址的行,您可能还希望将它们拆分,因此您会得到一个只有 MAC 地址的变量(否则 -contains/-in 不会工作):$hostname, $string = $pcname[$i] -split '\s+'.

标签: string powershell substring


【解决方案1】:

如何使用哈希表将 MAC 作为键,将 pc 名称作为值。

$MyMACs = Get-WmiObject win32_networkadapterconfiguration|Select -Expand MacAddress
$MyMACs

$PcHash = @{}
ForEach ($Row in (Get-Content '.\pcliste.txt')) {
  $PcHash.Add($Row.Split(' ')[1],$Row.Split(' ')[0])
}
ForEach($Mac in $MyMACs){
  IF ($PcHash[$Mac]){
    "Found {0} for MAC {1}" -f $PcHash[$Mac],$Mac 
  }
}

或者更基本的

$MyMACs = Get-WmiObject win32_networkadapterconfiguration|Select -Expand MacAddress
ForEach($Mac in $MyMACs){
   Select-String -Path '.\pcliste.txt' -Pattern $MAC|ForEach-Object{$_.Line}
}

【讨论】:

    【解决方案2】:

    尝试这样修改:

    $string =  $pcnamen[$i] -split " "
    if ($macadresse -contains $string[1]) {
    

    你可以像这样简化你的代码:

    $pcnamen = import-csv $pcliste -Delimiter ' ' -Header Computer, Mac
    
    Get-WmiObject Win32_NetworkAdapterConfiguration | %{
    $Mac=$_.macaddress
    $pcnamen | where Mac -eq $Mac 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-05
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多