Data Networking Blog
Blog for Admins

Powershell – Move files older than given days

Standard

Script below will move files from source to destination that match the given extension or all files if no extension is provided. The files older then 30 days are moved by default. you can specify the number of days using the -olderthandays parameter.

[CmdletBinding()]
param (
[Parameter(Mandatory=$true)][string]$source,
[Parameter(Mandatory=$true)][string]$destination,
[string[]]$exten=".*",
[int]$olderthandays = 30
)
$lwt = (get-date).AddDays(-$olderthandays)
if(!(Test-Path $source)){
Write-Output "Source directory does not exist."
exit
}
if(!(Test-Path $destination)){
Write-Output "Source directory does not exist."
exit
}
if($olderthandays -lt 0){
Write-Output "You can't provide a negative number of days. If you want everything deleted simply provide 0 for number of days."
exit
}
for ($i=0;$i -lt $exten.count;$i++){
if(!$exten[$i].StartsWith(".")){
$exten[$i] = "."+$exten[$i]
}
}
try{
foreach ($e in $exten){
Get-ChildItem $source -ErrorAction Stop -Filter "*$e" | ?{$_.LastWriteTime -lt $lwt} |
Move-item $_.FullName $destination -ErrorAction Stop
}
}
catch{
Write-Output "Something went wrong while moving items. Aborted operation."
}

Have fun.

August 3, 2016 PowerShell, Script, Uncategorised, Windows Jd
Font Size
Decrease Size Default Size Increase Size
Select Skin
Select Underlay Background
Select Overlay Background
Scheme Switcher Toggle