Home > OS >  Powershell - Find a specific file by name recursively in folder\folders
Powershell - Find a specific file by name recursively in folder\folders

Time:02-18

doing some scripting fun with looking for specific file by input. i want to search specific file by name for example: "abc*" with the prefix either it will be abc.txt, or abc.doc, or what ever... search recursively in folders, and print if it exists or not. here is the script i've got so far:

[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
} 

but all it does is printing list of the files and " - Not Found". and i do have files named "abc.txt" and "abc.doc" and many many more files. oh yeah and the reason the "find files" script is so long, its because i want to use this powershell script later on a build, and crush it if files doesnt exists.

any ideas whats wrong here?

CodePudding user response:

Either have your function return what was entered in the box and use that or remove that function completely as I have done below:

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.."
}

As you can see, you don't need to use Test-Path, because all files returned by Get-ChildItem of course do exist.

  • Parameter -Filter here is used with wildcards to search for files with $itemName in their name
  • Adding switch -File makes sure only files are searched, not folders aswell
  • Surrounding Get-ChildItem with @() forces the result to be an array, so you can work with the .Count property
  • Related