top of page
  • Writer's pictureshishir kushawaha

PowerShell to search specific file in entire disk

Is there a way to utilize Windows PowerShell to search for a file that I saved somewhere on my computer but cannot locate?
Is there a method to locate a file throughout the entire disk and remove it along with its parent folder?

If you have any such question in your mind, then find the PowerShell solution to get the answer of it.

  • Retrieve a list of drives on your disk using the Get-PSDrive cmdlet. Filter the results to include only drives with the 'FileSystem' provider.

$listOfDrives=(get-psdrive | ? { $_.provider -match 'FileSystem'}).root
  • Search for the desired file recursively across all the drives using the Get-ChildItem cmdlet. Specify the list of drives obtained in the previous step as the -Path parameter value. Use the -Filter parameter to specify the file name or pattern to search for. Add the -Recurse switch to search through all subdirectories. Use -ErrorAction SilentlyContinue to suppress error messages and -Force to bypass any restrictions.

$filePath=Get-ChildItem -Path $listOfDrives -Filter $filename -Recurse -ErrorAction SilentlyContinue -Force
  • Perform the desired actions on the files found. If you want to delete the file along with its parent folder, use the Remove-Item cmdlet.

Find the completed script.

$listOfDrives=(get-psdrive | ? { $_.provider -match 'FileSystem'}).root
$filePath=Get-ChildItem -Path $listOfDrives -Filter $filename -Recurse -ErrorAction SilentlyContinue -Force
if ($filePath -ne $null)
    write-host "Below path are found for $filename:"
    $parentFolder = $filePath.Directory.FullName
    Remove-Item -Path $parentFolder -Recurse -Force
    Write-Host "File $filename and its parent folder have been successfully deleted."
    Write-Host "File $filename not found."

Ensure you replace $filename with the actual name or pattern of the file you want to search for and delete.

619 views6 comments

Recent Posts

See All

Powershell functions are blocks of reusable code that can be executed whenever needed within a PowerShell script. Functions are an essential part of PowerShell scripting, as they provide several benef

Small and simple changes can sometimes have a significant impact on a large audience. One such example is the integration of a Text-to-Speech function. People desire a smarter and more meaningful inte

bottom of page