Requirements:
Folder structure : Reports>Reports A>Prior Periods
>Report (XLS,ZIP,PDF etc)
Reports> Reports B>Prior Periods
>Report (XLS,ZIP,PDF etc) and so on..
Everymonth (BD 1 to 5) I need to move Report into Prior Period>yyyyMM(created dynamically where MM will be current month -2..so for e.g If I move reports on April 1, 2015 the folder will be 201502). I have got this far. Now, what i want is to rename Report with yyyyMM(201502) appended to file name while moving in Prior Periods>201502. Here is what I have done so far.
P.S. This is my first attempt learning powershell by trial and error. The code is pieces stiched together from different sources to work plus plugged in trials i did. Please, guide if there is redundant code in it.
param(
[Parameter(
Mandatory = $true,
Position = 0,
HelpMessage = "Root of the folders or share to archive"
)]
[String] $source,
[Parameter(
Mandatory = $false,
Position = 1
)]
[int] $days = 32
)
$currentDate = [datetime]::Now
$currentDay = $currentDate.Day
$PreviousMonthEndDate = Get-Date $currentDate.AddDays(-$currentDay*2) -Hour 11 -Minute 59 -Second 59; # go back two months' end date
[string]$Target=$Source+'\Prior Periods\'+$PreviousMonthEndDate.ToString("yyyyMM");
if(!(Test-Path -Path $Target )){
New-Item -ItemType directory -Path $Target
};
Z:\ProdRef\Reports\SAGBBH~1
# Get all the files from the source path, that are not shortcuts and older than the days set
Get-ChildItem $source -Exclude "Prior Periods" -Recurse |
Where {$_.FullName -notlike "*\Prior Periods*" | #Trying to exclude History folder from the list of directories.
ForEach-Object {
# For each file build the destination path
$dest = $_.fullname -replace ([regex]::escape($source)), ($Target) }
# Check if the destination file path has the parent directory, if not create it
$parent = split-path $dest
if(!(test-path $parent)){
[void] (new-item -Path (split-path $parent) -Name (split-path $parent -leaf) -ItemType directory)
}
# Try to move the file into the destination
Move-Item -Path $_.fullname -Destination ($Target) -force }
Executing this file as C:\Sheelscr\ReportArch.ps1 -source C:\Reports\ReportA; C:\Sheelscr\ReportArch.ps1 -source C:\Reports\ReportB; and so on..
Any help would be greatly appreciated.