【问题标题】:using mac address in filepath - file not found?在文件路径中使用 mac 地址 - 找不到文件?
【发布时间】:2017-08-09 09:20:51
【问题描述】:
$test = @(gwmi win32_networkadapterconfiguration | select macaddress ) 
$test | ForEach-Object {

Write-Host $_.macaddress
$mac = $_.macaddress -replace ":", ""
$mac.Trim()
If (Test-Path "x:\$Mac") { $computer = $mac }

$Logfile = "x:\$Computer\$Computer.Log"
$File = "x:\$computer\$computer.ini"
$computer
$CompName = Get-Content $File | Select-Object -index 0
}

因此,即使 $file 存在,上述脚本也不会找到它。 x:\64006A849B90\64006A849B90.ini 存在,但我明白了

错误:获取内容:找不到路径“X:\64006A849B90\64006A849B90.ini”,因为它不存在。

任何人都知道我为什么不能使用它 - 我知道它与 $mac 值有关并确保它是一个字符串,但我已经尝试过 $mac.ToString() [String]$mac 并修剪它,但它不会看到路径 - 有什么想法吗?谢谢

奇怪的是值被拾取,因此 mac 地址在路径中,但如果有意义,它不会找到路径。

【问题讨论】:

  • 所以如果你运行它,你会在结果中看到文件吗? Get-ChildItem "X:\64006A849B90"
  • 嗨,马特,如果我运行这个 Get-ChildItem "X:\$computer" 我会得到 X:\ 的内容,而不是 x:\64006A849B90 如果我运行 gci x:\64006A849B90 它可以工作,但我认为value 必须是一个变量 - 它与 $computer = $mac 相关 - 但我无法解决
  • 所以$computer 为空。这是根据Test-Path "x:\$Mac" 的结果设置的。如果你在 if 中运行那个 not 会发生什么,就像我输入它一样。它返回假吗?我怀疑确实如此,这就是$computer 为空的原因。话虽如此,我不知道您更改变量的名称是什么。为什么不继续使用$mac
  • 返回 True - 困惑.. 如果我测试路径 x:\$computer 它返回 false。所以 $computer = $mac 没有占用 -
  • 取决于您在哪里进行测试。您是否在 if 语句之后尝试?此外,这不重要,因为它应该没有效果,您在 $mac 上使用 .trim() 但不要将其保存回来,所以如果需要,您应该 $mac=$mac.trim() (代码可以使用清理,但仅供参考)。

标签: arrays string powershell object


【解决方案1】:

我认为您可能还有其他问题,但假设您的文件已命名并存在于您期望的唯一问题是潜在的空值。

您是否有任何没有 MAC 地址的适配器?我现在有3个。使用您的代码,它将尝试处理这些。如果您不知道这些,我可以看到这是一个问题。小代码更新即可轻松修复

# Get the populated macs from all network adapters
$macs = Get-WmiObject win32_networkadapterconfiguration | Select-Object -ExpandProperty macaddress

ForEach($mac in $macs){
    $mac = $mac.replace(":","")
    $macFile = "x:\$mac\$mac.ini"
    if(Test-Path $macFile){
        # The ini file exists 
        $computer = Get-Content $macFile | Select-Object -Index 0
    } else {
        # Cant find the file
    }

    $computer
}

这可以进一步简化,但我不想一次做太多。

通过使用Select-Object -ExpandProperty macaddress,我们仍然会得到空值,但它们会被管道丢弃,因此$macs 将只包含实际 MAC 字符串。

整个$computer = $mac 应该可以工作,但它是多余的,所以我从您的代码中删除了该逻辑。

【讨论】:

    猜你喜欢
    • 2020-03-13
    • 2018-02-23
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多