通過輸入查找特定檔案來做一些腳本撰寫的樂趣。我想按名稱搜索特定檔案,例如:帶有前綴的“abc *”,它將是 abc.txt,或 abc.doc,或者任何...在檔案夾中遞回搜索,并列印它是否存在。這是我到目前為止的腳本:
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
Function Get-ItemName {
$Global:ItemName = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a Filename', 'File Name')
}
Get-ItemName
$itemList = Get-ChildItem "\\path_of_folder_with_many_files" -Recurse
$checkItems = 'true'
foreach ($item in $itemList) {
if ((Test-Path -LiteralPath $item) -eq $true -and (Name -like $ItemName)) {
Write-Host "$item - Found" -ForegroundColor Greed
}
elseif ((Test-Path -LiteralPath $item) -eq $false) {
Write-Host "$item - Not Found" -ForegroundColor Red
$checkItems = 'false'
}
}
if ($checkItems -eq $false){
echo ""
Write-Host "Some files was not found, Build Failed" -ForegroundColor Red
exit 1
}
但它所做的只是列印檔案串列和“-未找到”。我確實有名為“abc.txt”和“abc.doc”的檔案以及更多檔案。哦,是的,“查找檔案”腳本這么長的原因,是因為我想稍后在構建中使用這個 powershell 腳本,如果檔案不存在,則粉碎它。
有什么想法嗎?
uj5u.com熱心網友回復:
要么讓你的函式回傳在框中輸入的內容并使用它,要么完全洗掉該函式,如下所示:
Add-Type -AssemblyName Microsoft.VisualBasic
$itemName = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a Filename', 'File Name')
if (![string]::IsNullOrWhiteSpace($itemName)) {
# only search for files if there was anything entered in the box
$itemList = @(Get-ChildItem "\\path_of_folder_with_many_files" -Filter "*$itemName*" -File -Recurse)
# now do something with the array of FileInfo objects
# for demo just show how many files were found using the $itemName
Write-Host "Found $($itemList.Count) files with search name '$itemName'"
}
else {
write-host "Nothing was entered in the inputbox.."
}
如您所見,您不需要使用Test-Path,因為 Get-ChildItem 回傳的所有檔案當然都存在。
- 此處的引數
-Filter與通配符一起使用以搜索$itemName名稱中的檔案 - 添加開關
-File確保只搜索檔案,而不是檔案夾 - 圍繞 Get-ChildItem
@()強制結果為陣列,因此您可以使用該.Count屬性
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/428275.html
標籤:电源外壳
上一篇:Azure突觸部署失敗
