Troubleshooting a scheduled script

This topic contains 3 replies, has 4 voices, and was last updated by Profile photo of Sam Boutros Sam Boutros 4 months, 2 weeks ago.

  • Author
    Posts
  • #65856
    Profile photo of marius
    marius
    Participant

    I created a PowerShell script on a Windows Server 2008 R2 server and it works fine when launched interactively.
    I created a scheduled task to launch the same script every hour and it looks it is completed, but I don't see the expected results.
    So, I presume that something goes wrong during the scheduled execution or that I made some mistake while creating the scheduled task.
    How can I troubleshoot the scheduled execution to detect the problem?
    If I insert some write-host statements to debug the script where are they written?
    Regards
    marius

  • #65859
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    The common issues are credentials are different than what was used to test the task. To keep things simple to troubleshoot, you can leverage:

    Add-Content -Path "C:\troubleshoot.log" -Value "Step 1"
    

    Make sure the creds have permissions to the log.

  • #65860
    Profile photo of Ron
    Ron
    Participant

    I had a similar problem, also on 2008 R2. I could not get the working directory to take, I had to use full path names for everything, which I didn't want to do. I finally gave up, wrote a .bat file to call the PS script and scheduled the .bat file instead. Then everything worked as it should. As a bonus, I could make changes to the .bat file without having to changed the scheduled task, enter the service account password again, etc.

  • #65871
    Profile photo of Sam Boutros
    Sam Boutros
    Participant

    To schedule a PS script I recommend using the SCHTASKS.EXE tool as in:

    # To schedule a PowerShell script:
    
    $ScriptPath = 'C:\Sandbox\Monitor-Backup3.ps1'
    $TaskName   = 'BackupMonitor'
    $TaskRun    = "powershell.exe -NoLogo -NonInteractive -WindowStyle Hidden -Command ""$ScriptPath""" 
    
    # Example: Weekly on Sundays at 2 AM
    SCHTASKS.EXE /Create /S $Env:COMPUTERNAME /RU SYSTEM /SC WEEKLY /D SUN /TN $TaskName /TR $TaskRun /ST 02:00 /RL HIGHEST /F 
    break
    
    # Example: Daily at 7 AM
    SCHTASKS.EXE /Create /S $Env:COMPUTERNAME /RU SYSTEM /SC DAILY /TN $TaskName /TR $TaskRun /ST 07:00 /RL HIGHEST /F 
    break
    
    # Run now:
    SCHTASKS /Run /TN "\$TaskName"
    break 
    
    

    To check whether the script worked or not, or whether it did what it's supposed to do, I recommend re-writing the script to log its actions to text file. I use this write-log function.

You must be logged in to reply to this topic.