Reputation: 601
I'm using the following to copy/move files into archive folders.
It will later be adapted to pull down ISS logs and extended to zip them.
My problem is that:
Copy-Item $Somefile –Destination $SomeLocation
Results in the file being renamed during the copy in place of the directory I would like to copy it into.
I have added some Test-Path Statements to make directories for me but I understand that PS should be be able to do that maybe with an extra switch or definition?
#Declare Source and Destination
$Dest = $env:USERPROFILE+"\Desktop\H drive"
$SourceLocation = “H:”
ForEach ($SourceSubDir In Get-ChildItem $SourceLocation -Directory){
#Various Sub Directories Transposed to Destination
$DestSubDir = $SourceSubDir.Fullname.Replace($SourceLocation, $Dest)
#Create a Filtered List of Files
$TargetFiles = Get-ChildItem $SourceSubDir.FullName
#Loop Through and Move Filtered Files
ForEach($File In $TargetFiles){
$LastMonth = $((Get-Date).AddMonths(-1))
$DateModifiedDir = $($DestSubDir+'\'+$LastMonth.ToString('yyyy\,M')+'Archive')
If($File.LastWriteTime.Month -eq $LastMonth.Month){
#Create Subdirectory if not Existant
If(-Not(Test-Path $DestSubDir)){
New-Item $DestSubDir -ItemType Directory
}
#Create Date Modified Subdirectory if not Existant
If(-Not(Test-Path $DateModifiedDir)){
New-Item $DateModifiedDir -ItemType Directory
}
Copy-Item $File.FullName –Destination $DateModifiedDir -WhatIf
}
}
}
Upvotes: 0
Views: 194
Reputation: 200293
If the destination is a folder: always append a trailing backslash to prevent the copied item from being renamed in case the destination folder is missing.
$dst = "$env:USERPROFILE\Desktop\H drive"
$src = "H:"
Get-ChildItem $src | Copy-Item -Destination "$dst\"
However, looking at your script wouldn't robocopy
be a better choice for this task?
$src = 'H:\'
$dst = "$env:USERPROFILE\Desktop\H drive\{0:yyyy,MM}" -f $now.AddMonths(-1)
$now = Get-Date
$start = $now.AddMonths(-1).ToString("yyyyMM01")
$end = $now.AddDays(-($now.Day)).ToString("yyyyMMdd")
& robocopy $src $dst /s /maxage:$start /minage:$end
Upvotes: 2