1

I am attempting to iterate over many task scheduler entries to modify the task arguments. We have many servers running simultaneously launched scripts, all need to be reachable on the console if a process needs attention.

Ideal is to launch minimized with start /min or powershell -window minimized

I am testing against one sample task. My code so far looks like

$PREFIX = "-window minimized"
$taskPath = "\somepath\"
Get-ScheduledTask -CimSession "servername" -TaskPath $taskPath -TaskName "mytask" | ForEach-Object {

  $actions = $_.Actions
  $actions New-ScheduledTaskAction -Execute "powershell" -Argument "${PREFIX} ${actions}"
  Set-ScheduledTask -CimSession "servername" -TaskPath $taskPath -TaskName $_.TaskName -Action $actions
}

This works excepting I cannot get to the old command arguments. Always I get as new arguments with my prefix and then 'MSFT_TaskExecAction' following. This fails against a multi-step task resulting in only one bad step afterwards (and MSFT_TaskExecAction). Thanks all.

1 Answer 1

2

The Actions property contains a list of action instances - not just their arguments - for that you'll want the Arguments property on one of the contained actions:

$actions = $_.Actions |ForEach-Object {
  if ($_.Execute -match 'powershell') {
    # a powershell task, let's create a new one with the prefix
    $newTaskActionArgs = @{ Execute = 'powershell'; Arguments = "${PREFIX} $($_.Arguments)" }
    if ($_.WorkingDirectory) { 
      # make sure to copy the initial working directory if set too
      $newTaskActionArgs['WorkingDirectory'] = $_.WorkingDirectory
    }
    New-ScheduledTaskAction @newTaskActionArgs
  }
  else {
    # leave action as-is
    $_
  }
}

Set-ScheduledTask ... -Action $actions
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.