Powershell to copy the folder and files

Kalaimani Thirupathi 411 Reputation points
2021-04-15T13:27:10.827+00:00

Dear All,

Currently using the below script to copy the single file but I need to copy folder, subfolder and files also. Can you someone help me with this

and I need to see the progress of the copy

$sourceFiles = Read-Host "Enter The Restored location with file Name"
$rootDestFolder = Read-Host "Enter The User Request Restore Location"
$resuilt =foreach($sourceFile in $sourceFiles){
$filesplit = $sourceFile.split("\")
$splitcount = $filesplit.count
# This example strips the drive letter & first folder ( ex: E:\Subfolder\ ) but appends the rest of the path to the rootDestFolder
$destFile = $rootDestFolder + "\" + $($($sourceFile.split("\")[2..$splitcount]) -join "\")
# Output List of source and dest
Write-Host ""
Write-Host "Source File Location : $sourceFile " -ForegroundColor Green
Write-Host "Destination File Location : $destFile " -ForegroundColor yello
# Create path and file, if they do not already exist
$destPath = Split-Path $destFile
If(!(Test-Path $destPath)) { New-Item $destPath -Type Directory }
If(!(Test-Path $destFile)) { Copy-Item $sourceFile $destFile -recurse }
}

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Andreas Baumgarten 129.5K Reputation points MVP Volunteer Moderator
    2021-04-15T16:28:10.933+00:00

    Hi @Kalaimani Thirupathi ,

    the easiest way to copy folder, subfolder and files is this:

    Copy-Item -Path "C:\sourcefolder" -Destination "e:\targetfolder" -recurse -Force  
    

    To get a progess bar you can try the answer from MichalGajda here:
    https://social.technet.microsoft.com/Forums/windowsserver/en-US/c957ca7a-088e-40fb-8ce6-23da4d0753bb/progress-bar-for-copied-files-in-powershell?forum=winserverpowershell

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    4 people found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.