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.


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.



Sending Email using Power Shell script

Below are the two ways which you can use to send an email using power shell

Way 1:

$EmailFrom = “abc@sample.com”
$EmailTo = “xyz@smaple.com”
$Subject = “Test Email Using Power Shell”
$Body = “Hi, This is test email.”
$SMTPServer = “smtp.server”
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“”, “”);
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

Way 2:

Send-MailMessage -From “abc@sample.com” -To “xyz@sample.com” -SmtpServer “SmtpServerIP” -Subject “Subject for Email” -Body “Email Body” -BodyAsHtml

Copy file(s) from one location to another using Power Shell script

Below is the code to copy the file(s) from one location to another by reading the file name(s) from the text file.

$SourcePath = 'D:\Source\'
$DestinationPath = 'D:\Destination\'
foreach ($Trans in get-content D:\FileList.txt) {
        $fileNames  = Get-ChildItem -Recurse -Force $filePath -ErrorAction SilentlyContinue | Where-Object { ( $_.Name -like "*$fileName*") }

        foreach ($F in $fileNames){
                $fileName = $F.Name
                $fullpath = $SourcePath + $fileName
                Copy-Item -Path $fullpath  -Destination $DestinationPath