2017-03-17 141 views
0
$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 
} 

因此,上述腳本即使存在,也不會找到$文件。在X:\ 64006A849B90 \ 64006A849B90.ini是存在的,但我得到這個在文件路徑中使用MAC地址 - 找不到文件?

錯誤:獲取內容:找不到路徑「X:\ 64006A849B90 \ 64006A849B90.ini」,因爲它不存在。

任何人都知道爲什麼我不能使用這個 - 我知道它與$ mac值有關,並確保它的一個字符串,但我已經試過$ mac.ToString()[String] $ mac並修剪它,它會沒有看到路徑 - 任何想法?謝謝

奇怪的是價值正在拾起,因此MAC地址是在路徑,但它不會找到路徑,如果這是有道理的。

+0

所以如果你運行這個,你會在結果中看到文件? 'Get-ChildItem「X:\ 64006A849B90」' – Matt

+0

嗨馬特如果我運行此Get-ChildItem「X:\ $計算機」我得到的X:\的內容不是x:\ 64006A849B90如果我運行gci x:\ 64006A849B90它工作,但我的價值必須是一個變量 - 它的東西與這個$電腦= $ mac - 但我不能工作了 – LDStewart

+0

所以'$電腦'爲空然後。這是根據這個「測試路徑」x:\ $ Mac「'的結果設置的。如果在if中運行該_not_會發生什麼情況,但正如我輸入它那樣。它會返回錯誤嗎?我懷疑它是這樣的,這就是爲什麼'$ computer'爲空。這就是說,我不知道你爲改變變量名稱而煩惱。爲什麼不直接繼續使用'$ mac'? – Matt

回答

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應該已經工作,但它是多餘的,所以我從你的代碼中刪除了邏輯。