PowerShell copy specific file within a folder and keep folder structure

51 Views Asked by At

I need to copy a folder named "SystemData" that lives within other folders and from that "SystemData" folder I have many *.xml files. I want to copy the *.xml files to another location while keeping the folder structure. I have been trying to do this using robocopy but failed miserably.

I was wondering if someone could help me creating a powershell script using robocopy to copy the *.xml files within that folder to another location while preserving the folder structure

I appreciate your help.

I am using the below code

$sourceDir = 'C:\Users\peter.franca\Desktop\ProcessedProducts'
$targetDir = 'C:\Users\peter.franca\Desktop\CopiedFiles\ProcessedProducts'

echo "Backup Started at " > C:\SystemDataBackup.Log
Get-Date >> C:\SystemDataBackup.Log

Get-ChildItem $sourceDir -filter "*.xml" -recurse | Where-Object { $_.DirectoryName -like "*SystemData*" } | `
    foreach{
        $targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length);
        New-Item -ItemType File -Path $targetFile -Force;
        robocopy $_.FullName $targetFile /S /COPY:DT
    }

echo "Backup Finished at " >> C:\SystemDataBackup.Log
Get-Date >> C:\SystemDataBackup.Log
1

There are 1 best solutions below

1
TheGameiswar On
Copy-Item -Path "$source" -Destination "$dest" -Verbose -Force   -filter "*.xml" -Recurse

Copy-Item will create the folder for you,if source is a folder