I am trying to create a task with the following PS script:
$locations="$env:userprofile\Desktop\New folder (2)","$env:userprofile\Desktop\New folder (3)"
$Daysback = "-30"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
foreach ($location in $locations) {Get-ChildItem $location -Recurse | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item}
The new folders were created for testing, eventually it should be Downloads folder.
When running script locally, using path C:\Users\name.lastname\Desktop...
the script works fine and deletes the files in the correct directory. However, I have to check manually by going to C:\Users\name.lastname\Desktop...
to find that out. The "New folder (2)" and "New folder (3)" on my desktop still have the files (which are older than 30 days as the script is written) after applying the GPO to my machine. When I check the folder path (C:\Users\name.lastname\OneDrive - tekexperts.onmicrosoft.com\Desktop
) I started to suspect that the variable $env:userprofile
is finding the One Drive synced folders on my Desktop and consequently not deleting anything.
I would really appreciate it if somebody can advise if it is possible for my script to search for the exact proper system folders, instead of synced ones.
Thank you in advance.