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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s