none
Task Scheduler PowerShell Script RRS feed

  • Question

  • I have a script that finds a specific process, if it is running, terminate, wait x seconds, run the program again. When I test in PowerShell, it works as designed. However, I add the script to Task Scheduler it does not work. 

    Script Example:

    (Get-WmiObject -Class Win32_Process -Filter "Name = 'notepad.exe'").Terminate();
    Start-Sleep 10
    Start-Process -FilePath "C:\Windows\notepad.exe"

    Not sure if that is the correct path to start-process but it's just an example. 

    Task Scheduler Setup (Export XML):

    <?xml version="1.0" encoding="UTF-16"?>
    <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
      <RegistrationInfo>
        <Date>2019-10-15T16:02:32.6662873</Date>
        <Author>Domain\Username</Author>
        <URI>\RestartNotepadDaily</URI>
      </RegistrationInfo>
      <Triggers>
        <CalendarTrigger>
          <StartBoundary>2019-10-15T04:00:00</StartBoundary>
          <Enabled>true</Enabled>
          <ScheduleByWeek>
            <DaysOfWeek>
              <Monday />
              <Tuesday />
              <Wednesday />
              <Thursday />
              <Friday />
            </DaysOfWeek>
            <WeeksInterval>1</WeeksInterval>
          </ScheduleByWeek>
        </CalendarTrigger>
      </Triggers>
      <Principals>
        <Principal id="Author">
          <UserId>SID GUID HERE</UserId>
          <LogonType>Password</LogonType>
          <RunLevel>HighestAvailable</RunLevel>
        </Principal>
      </Principals>
      <Settings>
        <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
        <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
        <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
        <AllowHardTerminate>true</AllowHardTerminate>
        <StartWhenAvailable>false</StartWhenAvailable>
        <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
        <IdleSettings>
          <StopOnIdleEnd>true</StopOnIdleEnd>
          <RestartOnIdle>false</RestartOnIdle>
        </IdleSettings>
        <AllowStartOnDemand>true</AllowStartOnDemand>
        <Enabled>true</Enabled>
        <Hidden>false</Hidden>
        <RunOnlyIfIdle>false</RunOnlyIfIdle>
        <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
        <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
        <WakeToRun>false</WakeToRun>
        <ExecutionTimeLimit>PT2H</ExecutionTimeLimit>
        <Priority>7</Priority>
        <RestartOnFailure>
          <Interval>PT1M</Interval>
          <Count>20</Count>
        </RestartOnFailure>
      </Settings>
      <Actions Context="Author">
        <Exec>
          <Command>PowerShell.exe</Command>
          <Arguments>-NoProfile -ExecutionPolicy Bypass -File "c:\scripts\NotePadRestartDaily.ps1"</Arguments>
        </Exec>
      </Actions>
    </Task>

    Can anyone provide me with some suggestions on why I cannot get this to work? I have been bashing my brain for the past month trying different things to no success.

    Server Version: Windows Server 2015 Datacenter v1607 (Azure VM)

    Monday, November 11, 2019 10:58 PM

Answers

  • JRV,

    I am at a lost, I tried your 1 line command which once again, works great if I ran it directly in a PS window but not task scheduler.

    Either I am a total moron or Task Scheduler is a pain in the rear...

    The task scheduler must be running at an admin level.  The code will close ALL notepads.  Some programs may not close because they will throw an exception when killed.  Notepad won't do this.

    You need to catch the error so look in the event log and be sure task logging is enabled in the TS so you can see the exit codes.


    \_(ツ)_/

    • Marked as answer by Blacksuit1 Friday, November 15, 2019 8:38 PM
    Friday, November 15, 2019 4:16 PM
    Moderator

All replies

  • Your script can just be:

    Get-Process notepad | Stop-Process
    Start-Process notepad

    You will need to run as an admin with full privileges to stop processes from a task.


    \_(ツ)_/

    Monday, November 11, 2019 11:02 PM
    Moderator
  • JRV,

    I have tried that as well, no luck. 

    Get-Process notepad | Stop-Process
    Start-Sleep 10
    Start-Process notepad

    Works wonders while in PowerShell but not Task Scheduler. I see powershell.exe run for a brief second in task manager, then disappears with notepad not even closing.

    Monday, November 11, 2019 11:25 PM
  • Which proves that6 this has nothing to do with PowerShell and you never need to use sleep. 

    You can try this.

    Get-Process notepad -ErrorAction 0 | Stop-Process -Force


    \_(ツ)_/

    Monday, November 11, 2019 11:52 PM
    Moderator
  • JRV,

    I am at a lost, I tried your 1 line command which once again, works great if I ran it directly in a PS window but not task scheduler.

    Either I am a total moron or Task Scheduler is a pain in the rear...

    Friday, November 15, 2019 3:26 PM
  • JRV,

    I am at a lost, I tried your 1 line command which once again, works great if I ran it directly in a PS window but not task scheduler.

    Either I am a total moron or Task Scheduler is a pain in the rear...

    The task scheduler must be running at an admin level.  The code will close ALL notepads.  Some programs may not close because they will throw an exception when killed.  Notepad won't do this.

    You need to catch the error so look in the event log and be sure task logging is enabled in the TS so you can see the exit codes.


    \_(ツ)_/

    • Marked as answer by Blacksuit1 Friday, November 15, 2019 8:38 PM
    Friday, November 15, 2019 4:16 PM
    Moderator

  • I am at a lost, 

    Have your script create a transcript and see if it reports an error.

    start-transcript c:\scripts\ps.log
    (Get-WmiObject -Class Win32_Process -Filter "Name = 'notepad.exe'").Terminate();
    Start-Sleep 10
    Start-Process -FilePath "C:\Windows\notepad.exe"
    stop-transcript 

    If that doesn't work, then have cmd.exe launch Powershell and capture stdout and stderr. 

    Create a NotepadRestart.bat that runs your your script. 

    PowerShell.exe -NoProfile -ExecutionPolicy Bypass -File "c:\scripts\NotePadRestartDaily.ps1"
     

    In the task settings, run cmd.exe with these arguments.

    /c c:\scripts\NotepadRestart.bat 1> c:\scripts\NotepadRestart.log 2>&1 

    • Marked as answer by Blacksuit1 Friday, November 15, 2019 8:38 PM
    • Unmarked as answer by Blacksuit1 Friday, November 15, 2019 8:38 PM
    Friday, November 15, 2019 8:33 PM
  • Alright, I finally got this SOB to work!

    I disabled UAC, made sure the account was a local admin, and put the path in the "Start in (optional)" field. Not sure if all of that was necessary, don't care because the damn thing finally RUNS!

    Thank you everyone for suggestions, guidance, etc. It all helped me.

    Friday, November 15, 2019 8:38 PM