PowerShell to Copy Items and Retain Folder Structure


Welcome, fellow system admin.

Its been a while I have written any other article other than the 70-410 series that I have started.

The 70-410 series talks about all the objectives of the exam and will be a one stop destination for all my needs to refer the exam objectives.

If you wish to learn more about it, click here to know more.

Coming back to today’s article, I was recently having space issues on one of my drives and it was an important and needed immediate attention.

On further investigation, I found out that there were specific file types that were using up a lot of space.

So I decided to move those file types to a backup location. The key thing was to retain the Folder structure on the destination so that I could provide the details to the owner if required in future.

Well, it sounds easy, but for some reason Copy-Item could not create

Let us see the sample example below:

Get-ChildItem -Recurse -Include *.log | where {$_.LastWriteITime -lt “1/1/2015 12:00 AM”} | Copy-Item $_.FullName -Destination \\server1\share -Recurse

In the above example,I was first listing the files and folders recursively and selecting only the files which ended with .log extension.

Then I was limiting the search to the files whose modified date was less than 1/1/2015.

I then used Copy-Item to copy each file recursively to the destination path.

I also want you to be aware that I am using PowerShell version 5.0 here, so it did not cause any issues.

The actual task was to be done on a Windows Server 2008 R2 and the PowerShell version that I was left with was 2.0.

Now Copy-Item has some limitations when it comes to this version as it cannot create the Folder structure on the destination.

So I had to do some work around and after searching around Google for a while found a very solution.

$sourceDir = ‘E:\’
$targetDir = ‘\\server1\share’
Get-ChildItem $sourceDir -recurse -Include *.log | where {$_.LastWriteTime -lt “1/1/2015 12:00 AM”}| `
$targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length);
New-Item -ItemType File -Path $targetFile -Force;
Copy-Item $_.FullName -destination $targetFile

The first remained the same. Only before copying the Item I was first creating the folder structure on the Destination path.
 I hope that this has been informative and thank you for reading! 🙂

About Author

I am Adil Arif, working as a Technical Support Engineer at VMware as well as an independent blogger and founder of Enterprise Daddy. In my current role, I am supporting infrastructure related to Windows and VMware datacenters.

Leave A Reply

If so, please join the community.  I’d love to send you exclusive content right to your email, and I’ll send you a free copy of my book, VMware vSphere 6.0 Lab on Workstation too!
Enter your name and email below, and I’ll see you on the inside!