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

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.


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

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.




Posted September 27, 2014 by Izharuddin Shaikh in Power Shell

Tagged with

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: