我有一個腳本,用于從串列中跨多個驅動器搜索數百個檔案。它作業正常,因為它可以捕獲所有匹配項。唯一的問題是我需要查看它與擴展名匹配的檔案。一些背景故事...我們有與 Copybook 同名的程式。在大型機世界中并不少見。搜索檔案時,我必須通配搜索以捕獲所有相同名稱的檔案(減去擴展名)。然后我必須手動搜索匹配項以確定它們是字帖還是程式。當我嘗試向下面的腳本添加任何邏輯時,它會顯示整個檔案名陣列,而不僅僅是實際匹配項。任何人都可以幫助捕獲和顯示匹配的檔案及其擴展名嗎?也許它的位置也?
問候,-羅恩
#List containing file names must be wilcarded FILE.*
#Parent folder (Where to begin search)
$folder = 'C:\Workspace\src'
#Missing Artifacts Folder (Where Text file resides)
$Dir2 = 'C:\Workspace\Temp'
#Text File Name
$files=Get-Content $Dir2\FilesToSearchFor.txt
cd \
cd $folder
Write-Host "Folder: $folder"
# Get only files and only their names
$folderFiles = (Get-ChildItem -Recurse $folder -File).Name
foreach ($f in $files) {
#if ($folderFiles -contains $f) {
if ($folderFiles -like $f) {
Write-Host "File $f was found." -foregroundcolor green
} else {
Write-Host "File $f was not found!" -foregroundcolor red
}
}
uj5u.com熱心網友回復:
不是測驗整個檔案名串列是否包含目標檔案名 ( $folderFiles -like $f),而是將所有檔案加載到哈希表中,然后測驗目標檔案名是否作為鍵存在ContainsKey():
$fileTable = @{}
Get-ChildItem -Recurse $folder -File |ForEach-Object {
# Create a new key-value entry for the given file name (minus the extension) if it doesn't already exist
if(-not $fileTable.ContainsKey($_.BaseName)){
$fileTable[$_.BaseName] = @()
}
# Add file info object to the hashtable entry
$fileTable[$_.BaseName] = $_
}
foreach($f in $files){
if($fileTable.ContainsKey($f)){
Write-Host "$($fileTable[$f].Count) file(s) matching '$f' were found." -ForegroundColor Green
foreach($file in $fileTable[$f]){
Write-Host "File with extension '$($file.Extension)' found at: '$($file.FullName)'"
}
}
else {
Write-Host "No files found matching '$f'"
}
}
由于 不僅$fileTable包含名稱,還包含對具有由 回傳的名稱的原始檔案資訊物件的參考Get-ChildItem,因此您現在可以輕松訪問相關元資料(如Extension屬性)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380565.html
上一篇:如何使`Tee-Object`不在PowerShell中添加尾隨換行符?
下一篇:創建用于發送電子郵件的附件陣列
