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"}| `
foreach{
$targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length);
New-Item -ItemType File -Path $targetFile -Force;
Copy-Item $_.FullName -destination $targetFile
}
1 Comment
Hello, very nice script – I searched something similar few hours and this help me a lot. Thanks a lot for sharing this stuff.