I've got a script that deletes old temp files, and it works perfectly under the following scenarios:
- From the Console Host
- From the PowerShell ISE
- From the Run command. In other words, Start>>Run. Enter
powershell.exe -file C:\Users\<userprofile>\Delete-TempFiles.ps1
But I want to set it up as a Scheduled Task since it can take some time to finish. My understanding is that if a command works at the Run line, then I simply need to copy that command into the proper field in Task Scheduler. Namely, the 'Program/script' text box under the 'Actions' tab. The Scheduler moves the verbiage after 'powershell.exe' to the 'Arguments' field, and everything should be good. So saith Ed Wilson, Scripting Guy.
But something breaks. When launched regularly, the script gets server names from a text file, checks temp folders on each server, and deletes old files, like so:
Get-ChildItem -Path \\$server\C$\Windows\Temp -File | Where-Object {$_.LastAccessTime -lt $cutoffdate} | Remove-Item -Recurse
On every server I've tested, at least something is found and deleted, as expected. But when I set up the Scheduled Task, zero files are found/deleted.
After some troubleshooting, I discovered that when I click Start>>Run>>PowerShell, it opens to my user profile, but when Scheduled Task launches PowerShell, it opens to C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe
. Because my script was written to assume my source file was in my profile, PS couldn't find it. I thought that filling in the "Start In" text box in Scheduled Task would mean that PowerShell would open in that folder, but I guess not.
To fix that, I hard-coded the location of the source file in my script (ick) and I put Set-Location C:\Users\<userprofile>
at the top of my script. But that doesn't change anything.
I've also tried the following for Actions:
powershell -noprofile -noexit -executionpolicy bypass -file C:\Users\<userprofile>\Delete-TempFolders.ps1
Again, the script when launched as a task works normally except it fails to find or delete any old temp files. I simply can't figure out where it's failing.