powershell script to clean desktop code example

Example: powershell script to clean desktop

#Variables
$Age = 14 #Time since last file access in days
 
#Set desktop path
$SourcePath = [Environment]::GetFolderPath("Desktop")
 
#Get all files
$Files = (Get-ChildItem -Path $SourcePath -File)
 
#Select files that have not been opened since the specified number of days
$OldFiles = $Files | where {$_.LastAccessTime -le ((Get-Date).AddDays(-$Age))}
 
#Process identified files, if any
if ($OldFiles){
$TargetPath = $SourcePath + "\Archive\" + (Get-Date -Format yyyy-MM-dd)
New-Item -Path $TargetPath -ItemType Directory -Verbose
 
#Move files
$OldFiles | Move-Item -Destination $TargetPath -Verbose
}