在文件路径中使用mac地址 - 找不到文件?

时间:2017-03-17 17:38:29

标签: arrays string powershell object

$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地址位于路径中,但如果有意义,它将找不到路径。

1 个答案:

答案 0 :(得分:2)

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

你有没有没有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应该有效,但它是多余的,所以我从你的代码中删除了那个逻辑。