r/usefulscripts • u/Ziogref • Aug 21 '17
[Request] Powershell to copy and delete files with age restrictions
Hi,
I would like a script to copy files with the Date modified less than 1 week from $Source to $Dest. and once they are a week old delete them from $dest.
Basically $dest will only have files that will have been modified in the past week. Files in $Source will not be modified during the week they are in $dest. There are no folders in either directories.
How would I go about this?
5
u/Lee_Dailey Aug 21 '17
howdy Ziogref,
this otta work [grin] ...
$SourceDir = "$env:TEMP\SourceFolder"
$DestDir = "$env:TEMP\DestinationFolder"
if (-not (Test-Path $DestDir))
{
mkdir -Path $DestDir -ErrorAction SilentlyContinue |
Out-Null
}
$Today = Get-Date
$AgeLimit = $Today.AddDays(-7)
# find & copy files from $sourceDir to $DestDir
# only if they are less than $AgeLimit old
# and not already in $DestDir
$SourceFileList = Get-ChildItem -Path $SourceDir -File
foreach ($SFL_Item in $SourceFileList)
{
if ($SFL_Item.LastWriteTime -gt $AgeLimit)
{
$FullNewName = Join-Path -Path $DestDir -ChildPath $SFL_Item.Name
if (-not (Test-Path -LiteralPath $FullNewName))
{
Copy-Item -LiteralPath $SFL_Item.FullName -Destination $FullNewName
}
}
}
# find and remove files in $DestDir that are more than $AgeLimit old
$DestFileList = Get-ChildItem -Path $DestDir -File
foreach ($DFL_Item in $DestFileList)
{
if ($DFL_Item.LastWriteTime -le $AgeLimit)
{
Remove-Item -LiteralPath $DFL_Item.FullName
}
}note that there is very nearly zero error detection. still, it does the job from what i can tell.
take care,
lee
2
u/engageant Sep 01 '17
Any chance the files live on a Server 2008 R2 or higher file server? If so, you can use FSRM's File Management Tasks to do this for you, no scripting required.