我正在嘗試將Get-PSDrive磁盤使用的所有驅動器號放入一個回傳每個字母的字串中(有效)
我在使用$ISODeviceLetter變數將其用作搜索所有驅動器以查找.ISO檔案時遇到問題。
$ISODeviceLetter = Get-PSDrive | Select-Object -ExpandProperty 'Name' | Select-String -Pattern '^[a-z]:$'
$ISOLocation = Get-ChildItem -Path $ISODeviceLetter -Recurse -Include *.ISO
這是我得到的錯誤:
Get-ChildItem : Cannot find path 'C:\Users\Administrator\C' because it does not exist.
At line:1 char:16
... OLocation = Get-ChildItem -Path $ISODeviceLetter -Recurse -Include *. ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : ObjectNotFound: (C:\Users\Administrator\C:String) [Get-ChildItem], ItemNotFoundException
FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
我看到錯誤get-childitem是使用默認位置,即C:\Users\Administrator。
所需的輸出是$ISODriveLetter作為服務器上所有驅動器的路徑傳遞“C:”、“D:”、“E:”,因此可以搜索所有驅動器以查找.ISO檔案。
提前感謝您的幫助。
uj5u.com熱心網友回復:
問題在于,在參考驅動器時,必須使用冒號 ( :) 來區分它們以消除驅動器與常規檔案夾/檔案的歧義:
- 使用該
Foreach-Object命令將冒號附加到回傳的每個驅動器號。 - 將過濾器從 更改
-Include為-Filter,以加快FileSystemProvider-Filter實作的程序,并且您也不需要查找多個檔案。 - 還
-File為更高效的查詢添加了開關,因為.ISO擴展名與檔案相關聯。
$ISODeviceLetter = [array](Get-PSDrive |
Where-Object -FilterScript {$_.Name -match "^.$"}).Foreach{
$_.Name ':'
}
$ISOLocation = Get-ChildItem -Path $ISODeviceLetter -File -Recurse -Filter *.ISO
獎勵:您可以使用簡化語法來實作與上述相同的結果以獲得更好的可讀性:
$ISODeviceLetter = (Get-PSDrive).Where{$_.Name -match "^.$"} |
Select -exp Name | Foreach Insert -ArgumentList 1,':'
唯一真正的“缺點”是,您正在更多地使用管道。盡管它可能不會影響您在此示例中的回傳速度,但其他時間敏感的任務可能會使用管道對性能造成相當大的影響。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/374224.html
標籤:电源外壳
上一篇:如何修復PowerShell中的哈希文字中不允許出現空鍵
下一篇:組物件,獲取計數
