Loop through directory and sub directories to find file and copy using Power Shell script

In this article we will talk about how to search and copy the file using power shell by searching for file recursively inside file system directory.

Resolution:

1) Loop through Main directory for files

2) Loop through each sub directory inside main directory and so on.

3) Compare File Name with file searched inside the directories, if match found then copy the file and break the loop and search for another file.

Below is the example of Power Shell script.

$Source ='D:\SourceFolder'
$Dest = 'D:\DestinationFolder\'

$FilesandFolders = Get-ChildItem -Path $Source -Recurse

ForEach($Item in $FilesandFolders){
              ForEach($FileName In Get-Content D:\FileNames.txt){
                     if($fileName -eq $Item.Name){
                           Copy-Item -Path $Item.FullName -Destination $Dest
                           Break;
                     }
              }
}

Where -Recurse keyword along with Get-ChildItem force to get list recursively for all items.

Get-Content is the command to read the content of the file.

Copy-Item command used to copy the file from one location to another.

 

 

Advertisements

#copy-file-using-power-shell