0

I'm trying to make a script on a users pc that will run a PowerShell script once a week and clear out the contents of a users download folder.

i have tried the following scripts but cant get them to work.. Im not to familiar with PowerShell, so forgive me if the answer is easy.

I have tried the following scripts; they will work with users temp folder, but when I try to change it to downloads folder.

$CutOffDate = (Get-Date).AddDays(-7)
$AllTemp    = "$($Env:Downloads.Replace("$Env:Username",'*'))"
Get-ChildItem -path $AllTemp -Recurse | 
    Where-Object {$_.CreationTime -lt $CutOffDate} | 
    Remove-Item -Recurse -Force -ErrorAction SilentlyContinue

and

$CutOffDate = (Get-Date).AddDays(-7)
    Get-ChildItem -Path "C:\Users\*\Downloads\*.*" | Where-Object { $_.CreationTime -lt $CutOffDate } | Remove-Item

The first script throws errors and the second one says permission denied when I use a basics user profile. However if I use admin profile it wants to delete downloads content from admin user and not basic user. I'm unsure what do to - can anyone help?

3
  • 1
    In the description it says you're writing a script to clear out "a users download folder", but the code you've posted appears to attempt deletion of the contents of the downloads folder of every user... so, which one is it? Commented Jul 8 at 14:24
  • For the second script using Get-ChildItem -Path "C:\Users\*\Downloads\*.*" with the conditional where-object make it a schedule task that runs as SYSTEM. The schedule it to run once a week. Use Remove-Item "C:\Users\*\Downloads\*" -Recurse -Force; or some tweaked variation. Commented Jul 8 at 14:41
  • its the first one im not sure how to use powershell so thats the script i have been using Commented Jul 8 at 14:57

1 Answer 1

0
$CutOffDate = (Get-Date).AddDays(-7)
    Get-ChildItem $env:USERPROFILE\Downloads | Where-Object { $_.CreationTime -lt $CutOffDate } | Remove-Item -recurse

This will delete anything over 7 days old in the logged in users download contents

$CutOffDate = (Get-Date).AddDays(-7)
$AllTemp    = "$($Env:Temp.Replace("$Env:Username",'*'))"
Get-ChildItem -path $AllTemp -Recurse | 
    Where-Object {$_.CreationTime -lt $CutOffDate} | 
    Remove-Item -Recurse -Force -ErrorAction SilentlyContinue

this will delete anything over 7 days old in users temp folder and do the same thing why are the different dont know but it works!

Not the answer you're looking for? Browse other questions tagged or ask your own question.