Find a File in a Directory With PowerShell

This PowerShell post will show how to search and find a file inside a directory with a PowerShell foreach statement.

Foreach

The main idea behind this post is to learn how to use the foreach statement to go over several items and use an if statement to find a specific item.

In the following code, I have a directory that contains several files that I am searching for a specific file.

In the first line of code, I am loading the directory path into an array variable called folder. In the second line, I use a foreach statement to loop over the items (files). The if statement compares each item (files) to the file’s name that I’m looking for.

$folder = Get-ChildItem  -path "c:\code\files" 
foreach($item in $folder){

  if($item -like "file1.txt"){
     "File found"
   
   }
}

Using the above code, you can add an else statement or operations that will run due to a find or not find action.

For more PowerShell posts please visit the PowerShell category page.


Posted

in

,

by