[powershell] Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

I am struggling really hard to get this below script worked to copy the files in folders and sub folders in the proper structure (As the source server).

Lets say, there are folders mentioned below:

Main Folder: File aaa, File bbb

Sub Folder a: File 1, File 2, File 3

Sub Folder b: File 4, File 5, File 6

Script used:

Get-ChildItem -Path \\Server1\Test -recurse | ForEach-Object {
Copy-Item -LiteralPath $_.FullName -Destination \\server2\test |
Get-Acl -Path $_.FullName | Set-Acl -Path "\\server2\test\$(Split-Path -Path $_.FullName -Leaf)"

}

Output: File aaa, File bbb

Sub Folder a (Empty Folder)

Sub Folder b (Empty Folder)

File 1, File 2, File 3, File 4, File 5, File 6.

I want the files to get copied to their respective folders (Like the source folders). Any further help is highly appreciated.

This question is related to powershell powershell-2.0 powershell-3.0

The answer is


I wanted a solution to copy files modified after a certain date and time which mean't I need to use Get-ChildItem piped through a filter. Below is what I came up with:

$SourceFolder = "C:\Users\RCoode\Documents\Visual Studio 2010\Projects\MyProject"
$ArchiveFolder = "J:\Temp\Robin\Deploy\MyProject"
$ChangesStarted = New-Object System.DateTime(2013,10,16,11,0,0)
$IncludeFiles = ("*.vb","*.cs","*.aspx","*.js","*.css")

Get-ChildItem $SourceFolder -Recurse -Include $IncludeFiles | Where-Object {$_.LastWriteTime -gt $ChangesStarted} | ForEach-Object {
    $PathArray = $_.FullName.Replace($SourceFolder,"").ToString().Split('\') 

    $Folder = $ArchiveFolder

    for ($i=1; $i -lt $PathArray.length-1; $i++) {
        $Folder += "\" + $PathArray[$i]
        if (!(Test-Path $Folder)) {
            New-Item -ItemType directory -Path $Folder
        }
    }   
    $NewPath = Join-Path $ArchiveFolder $_.FullName.Replace($SourceFolder,"")

    Copy-Item $_.FullName -Destination $NewPath  
}

I had trouble with the most popular answer (overthinking). It put AFolder in the \Server\MyFolder\AFolder and I wanted the contents of AFolder and below in MyFolder. This didn't work.

Copy-Item -Verbose -Path C:\MyFolder\AFolder -Destination \\Server\MyFolder -recurse -Force

Plus I needed to Filter and only copy *.config files.

This didn't work, with "\*" because it did not recurse

Copy-Item -Verbose -Path C:\MyFolder\AFolder\* -Filter *.config -Destination \\Server\MyFolder -recurse -Force

I ended up lopping off the beginning of the path string, to get the childPath relative to where I was recursing from. This works for the use-case in question and went down many subdirectories, which some other solutions do not.

Get-Childitem -Path "$($sourcePath)/**/*.config" -Recurse | 
ForEach-Object {
  $childPath = "$_".substring($sourcePath.length+1)
  $dest = "$($destPath)\$($childPath)" #this puts a \ between dest and child path
  Copy-Item -Verbose -Path $_ -Destination $dest -Force   
}

one time i found this script, this copy folder and files and keep the same structure of the source in the destination, you can make some tries with this.

# Find the source files
$sourceDir="X:\sourceFolder"

# Set the target file
$targetDir="Y:\Destfolder\"
Get-ChildItem $sourceDir -Include *.* -Recurse |  foreach {

    # Remove the original  root folder
    $split = $_.Fullname  -split '\\'
    $DestFile =  $split[1..($split.Length - 1)] -join '\' 

    # Build the new  destination file path
    $DestFile = $targetDir+$DestFile

    # Move-Item won't  create the folder structure so we have to 
    # create a blank file  and then overwrite it
    $null = New-Item -Path  $DestFile -Type File -Force
    Move-Item -Path  $_.FullName -Destination $DestFile -Force
}

If you want to mirror same content from source to destination, try following one.

function CopyFilesToFolder ($fromFolder, $toFolder) {
    $childItems = Get-ChildItem $fromFolder
    $childItems | ForEach-Object {
         Copy-Item -Path $_.FullName -Destination $toFolder -Recurse -Force
    }
}

Test:

CopyFilesToFolder "C:\temp\q" "c:\temp\w"

Examples related to powershell

Why powershell does not run Angular commands? How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line? How to print environment variables to the console in PowerShell? Check if a string is not NULL or EMPTY The term 'ng' is not recognized as the name of a cmdlet VSCode Change Default Terminal 'Connect-MsolService' is not recognized as the name of a cmdlet Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet Change directory in PowerShell

Examples related to powershell-2.0

Extract the filename from a path Out-File -append in Powershell does not produce a new line and breaks string into characters Using PowerShell to remove lines from a text file if it contains a string PowerShell The term is not recognized as cmdlet function script file or operable program Can't install nuget package because of "Failed to initialize the PowerShell host" Powershell script to see currently logged in users (domain and machine) + status (active, idle, away) How to export data to CSV in PowerShell? powershell is missing the terminator: " PowerShell script to check the status of a URL How to upgrade PowerShell version from 2.0 to 3.0

Examples related to powershell-3.0

Check if a file exists or not in Windows PowerShell? Executing a batch file in a remote machine through PsExec Powershell get ipv4 address into a variable How can you test if an object has a specific property? PowerShell To Set Folder Permissions Using PowerShell to remove lines from a text file if it contains a string Powershell script to see currently logged in users (domain and machine) + status (active, idle, away) powershell is missing the terminator: " How to upgrade PowerShell version from 2.0 to 3.0 Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell