Author Posts

April 1, 2017 at 5:27 pm

Have set up scheduled task to delete temp files that are generated constantly. The schedule runs but the actual deleting does not. The delete command itself runs just fine.

$trigger = New-JobTrigger -Once -At 11:00 -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-TimeSpan -Hours 12)
$opts = New-ScheduledJobOption -RunElevated
$name = "oldLogsDeleteJob"
$limit = (Get-Date).AddMinutes(-5) 
$path = Split-Path -Path $env:temp
$action = { 
    Get-ChildItem -Path $path | Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit -and $_.Name -match "scoped_dir"} | Remove-Item -Force -Recurse
}


Register-ScheduledJob -Name $name -ScriptBlock $action -Trigger $trigger -ScheduledJobOption $opts

As I mentioned, if I run:

Get-ChildItem -Path $path | Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit -and $_.Name -match "scoped_dir"} | Remove-Item -Force -Recurse

The files vanish as they should.

I'm out of ideas. I've tried setting this up manually in Task Scheduler but the same thing happens.

April 1, 2017 at 8:26 pm

# To schedule a PowerShell script:

$ScriptPath = 'C:\scripts\ping-report-v3.ps1'
$TaskName   = 'PingReport'
$TaskRun    = "powershell.exe -NoLogo -NonInteractive -WindowStyle Hidden -Command ""$ScriptPath""" 

# Example: Hourly starting at 9 AM
SCHTASKS.EXE /Create /S $Env:COMPUTERNAME /RU SYSTEM /TN $TaskName /TR $TaskRun /SC HOURLY /ST 09:00 /RL HIGHEST /F 
#>

April 14, 2017 at 4:18 pm

Sam,

Thanks for the reply, I haven't had to use schtasks.exe in a very long time!
Apologies for not getting back sooner. I've been off work since the day I posted this! I'm going to test this later and check the results.

So am I just making it much more difficult for myself by trying to go the pure PowerShell way? I really don't know why it's not running the job as needed. That's what the "Job" CMDlets are for right?

April 15, 2017 at 12:55 am

I think one of the things that may be going on is – although the job is being registered – it's never being triggered. We could go into troubleshooting the trigger, but I think the easiest way to do this would be to add the -RunNow parameter, or use the Start-Job cmdlet to see if we can make it run in the first place.

Let me know if this works or not!

May 18, 2017 at 12:59 pm

Hey guys,

Apologies for not being in touch. I managed to get my schedule working. One of the points of confusion was calling the $env:temp

It goes to either /temp or /temp/2 in different cases for whatever reason so I just used the full path in quotes which worked for me.

I haven't had a chance to try your suggestion Bryce. I'll have a chance to try this out soon so I'll get back to you again when I do but for the time, going oldskool with TaskScheduler has done the trick for now 🙂