-CodeBlock not running in Register-ScheduledJob

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Bryce McDonald Bryce McDonald 2 weeks, 1 day ago.

  • Author
  • #67713
    Profile photo of Daniel Watson
    Daniel Watson

    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.

  • #67714
    Profile photo of Sam Boutros
    Sam Boutros
    # 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
    • #68740
      Profile photo of Daniel Watson
      Daniel Watson


      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?

    • #68755
      Profile photo of Bryce McDonald
      Bryce McDonald

      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!

You must be logged in to reply to this topic.