Home > Back-end >  Powershell New-ScheduledTaskAction - with inline command
Powershell New-ScheduledTaskAction - with inline command

Time:12-18

Im trying to create a scheduled task on a VM but with the actual command (Powershell command) within the task itself.

Here's what I have:

$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 3)
 
 $task = @{
    Action   = New-ScheduledTaskAction -Execute "powershell.exe" "-Command 'Get-Service -Name "Tssdis" | Where-Object {$_.Status -eq "Stopped"} | Restart-Service'"
    Trigger  = $trigger
    User     = "admin"
    TaskName = 'tssdis-restart'
    Description = 'Respawn tssdis process in event of failure'
    RunLevel    = 'Highest'
}

Register-ScheduledTask @task

Get-ScheduledTask | where{$_.TaskPath -eq "\"} 
Get-Service -Name "Tssdis" 

The task is added correctly - we can see that, but whenever I stop the tssdis process, it doesn't come backup.

The problem is the perhaps:

  1. The syntax of the command itself within the Action variable. I'm not sure if that's correct. Or
  2. The Syntax of the username -> Am I meant to give the syntax as DOMAIN\admin? If so, where can I find the DOMAIN name of that user?

I tried to change the double quotes to single quotes in the Command line. I tried also to change the User variable to User = "NT AUTHORITY\SYSTEM" - that didn't work either

CodePudding user response:

You're trying to have one set of doublequotes inside another. The programs args I get in task scheduler is -Command 'Get-Service -Name. The other quoted part becomes the working directory. The syntax coloring shows the quoting.

$task.action

Id               :
Arguments        : -Command 'Get-Service -Name
Execute          : powershell.exe
WorkingDirectory : Tssdis | Where-Object {.Status -eq Stopped} | Restart-Service'
PSComputerName   :

I assume the admin user exists. Note this runs every three minutes.

One way to re-quote it is to only use the single quotes in where-object. The get-service argument doesn't need quotes.

Action = New-ScheduledTaskAction -Execute "powershell.exe" "-Command Get-Service -Name Tssdis | Where-Object {$_.Status -eq 'Stopped'} | Restart-Service"

Or using the other version of where-object lets you drop all singlequotes:

Action = New-ScheduledTaskAction -Execute "powershell.exe" "-Command Get-Service -Name Tssdis | Where-Object Status -eq Stopped | Restart-Service"
  • Related