Register-ScheduledTask help needed

Windows 2012 R2 and Windows 2016 Servers

Powershell v4 & 5

Creating a scheduled task on each server was time consuming until I found how to due this in powershell.

My script is simple

import-module PSScheduledjob
$trigger = New-JobTrigger -Daily -At 7:30AM
$User = "MyDOM\Schedular"
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "c:\scripts\check_win_updates_scheduled.ps1"
Register-ScheduledTask -TaskName "Check Windows Updates" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest -Force 

This all works great

But I would like to add two more setting to the script but can not find it any where

The settings are

Set Run Weather user is logged on or not this is a check box

Configure for this would be Windows Server 2012 R2

Currently I need to modify each task to change these.

I have over 175 server to do this on would be helpful if I am just missing something.

 

Thank you,

 

Tom

 

 

 

 

Below help documentation will help you. Use this and -Setting parameter of New-ScheduledTask cmdlet.

Get-Help New-ScheduledTaskSettingsSet -Online for Configure for option. I couldn’t find an option to set to run “if user is not logged on”.

PS C:\PowerShell> Get-Help New-ScheduledTaskSettingsSet -Online

Get-Help : The online version of this Help topic cannot be displayed because the Internet address (URI) of the Help topic is not specified in the command code or in the help file for the command.

At line:1 char:1

  • Get-Help New-ScheduledTaskSettingsSet -Online

  • 
    
  • CategoryInfo : InvalidOperation: (:slight_smile: [Get-Help], PSInvalidOperationException

  • FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.GetHelpCommand

PS C:\PowerShell> Get-Help New-ScheduledTaskSettingsSet

NAME

New-ScheduledTaskSettingsSet

SYNTAX

New-ScheduledTaskSettingsSet [-DisallowDemandStart] [-DisallowHardTerminate] [-Compatibility {At | V1 | Vista | Win7 | Win8}] [-DeleteExpiredTaskAfter <timespan>] [-AllowStartIfOnBatteries] [-Disable]

[-MaintenanceExclusive] [-Hidden] [-RunOnlyIfIdle] [-IdleWaitTimeout <timespan>] [-NetworkId <string>] [-NetworkName <string>] [-DisallowStartOnRemoteAppSession] [-MaintenancePeriod <timespan>] [-MaintenanceDeadline

<timespan>] [-StartWhenAvailable] [-DontStopIfGoingOnBatteries] [-WakeToRun] [-IdleDuration <timespan>] [-RestartOnIdle] [-DontStopOnIdleEnd] [-ExecutionTimeLimit <timespan>] [-MultipleInstances {Parallel | Queue |

IgnoreNew}] [-Priority <int>] [-RestartCount <int>] [-RestartInterval <timespan>] [-RunOnlyIfNetworkAvailable] [-CimSession <CimSession>] [-ThrottleLimit <int>] [-AsJob] [<CommonParameters>]

ALIASES

None

REMARKS

Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.

– To download and install Help files for the module that includes this cmdlet, use Update-Help.

 

 

 

PS C:\PowerShell>

Do you have the info that you can post I seem not to be able to get any info on that configure for option

You would use -Compatibility for that option.

PS C:\scripts> $Stset = New-ScheduledTaskSettingsSet -Compatibility ‘Windows Server 2012 R2’
New-ScheduledTaskSettingsSet : Cannot process argument transformation on parameter ‘Compatibility’. Cannot convert
value “Windows Server 2012 R2” to type
“Microsoft.PowerShell.Cmdletization.GeneratedTypes.ScheduledTask.CompatibilityEnum”. Error: “Unable to match the
identifier name Windows Server 2012 R2 to a valid enumerator name. Specify one of the following enumerator names and
try again:
At, V1, Vista, Win7, Win8”
At line:1 char:54

  • … New-ScheduledTaskSettingsSet -Compatibility ‘Windows Server 2012 R2’
  •                                              ~~~~~~~~~~~~~~~~~~~~~~~~
    
  • CategoryInfo : InvalidData: (:slight_smile: [New-ScheduledTaskSettingsSet], ParameterBindingArgumentTransformationE
    xception
  • FullyQualifiedErrorId : ParameterArgumentTransformationError,New-ScheduledTaskSettingsSet

 

Do not think that is the one

-Compatibility has a list of allowed values, if you had read the doc properly -> [-Compatibility {At | V1 | Vista | Win7 | Win8}]

Yes but these are Windows 2012 R2 Servers

ALSO

 

What about this setting?

Set Run Weather user is logged on or not

 

 

 

Not all settings can be hit using that cmdlet or others like it. These are just XML files.

Get-ChildItem -Path 'C:\Windows\System32\Tasks'

You can manually create a task on a single server then Export it save and copy manually or directly write it to the others and just register it there.

Export-ScheduledTask 'TestTask' | 
out-file '\\TargetServer\c$\public\TestTask.xml'

Invoke-Command -ComputerName 'TargetServer' -ScriptBlock {
    Register-ScheduledTask -Xml (Get-Content 'C:\Users\public\TestTask.xml' | out-string) -TaskName 'TestTask'
}

… or you can script it, but you have to manipulate the XML file.

For Example:

# Create your task 
$A = New-ScheduledTaskAction –Execute 'powershell' -Argument 'Hello, from task scheduler'
$T = New-ScheduledTaskTrigger -Weekly -WeeksInterval 1 -DaysOfWeek Monday,Tuesday,Wednesday,Thursday,Friday -At 8am
$S = New-ScheduledTaskSettingsSet
$D = New-ScheduledTask -Action $A -Trigger $T -Settings $S
$Task = Register-ScheduledTask 'TestTask' -InputObject $D



# View the created task XML
Get-Content -Path 'C:\Windows\System32\Tasks\TestTask'  | Out-GridView


# capture the task to work with
$Task = Get-ScheduledTask -TaskName 'TestTask' 



# Step through the task information.
$Task | Select *


State                 : Ready
Actions               : {MSFT_TaskExecAction}
Author                : 
Date                  : 
Description           : 
Documentation         : 
Principal             : MSFT_TaskPrincipal2
SecurityDescriptor    : 
Settings              : MSFT_TaskSettings3
Source                : 
TaskName              : TestTask
TaskPath              : \
Triggers              : {MSFT_TaskWeeklyTrigger}
URI                   : 
Version               : 
PSComputerName        : 
CimClass              : Root/Microsoft/Windows/TaskScheduler:MSFT_ScheduledTask
CimInstanceProperties : {Actions, Author, Date, Description...}
CimSystemProperties   : Microsoft.Management.Infrastructure.CimSystemProperties


$ScheduleTaskKeys = 
'State',
'Actions',
'Author', 
'Date',
'Description',
'Documentation',
'Principal',
'SecurityDescriptor',
'Settings',
'Source',
'TaskName',
'TaskPath',
'Triggers',
'URI',
'Version',
'PSComputerName'

ForEach($TaskKey in $ScheduleTaskKeys)
{$Task.$TaskKey | Format-List -Force}

# View as JSON
$Task | ConvertTo-Json


# Example XML config
# Configuring triggers
$Task.Triggers | Format-List -Force


Enabled            : True
EndBoundary        : 
ExecutionTimeLimit : 
Id                 : 
Repetition         : MSFT_TaskRepetitionPattern
StartBoundary      : 2018-11-10T08:00:00
DaysOfWeek         : 62
RandomDelay        : P0DT0H0M0S
WeeksInterval      : 1
PSComputerName     :  




$Task.Triggers.Repetition | Format-List * -Force


Duration              : 
Interval              : 
StopAtDurationEnd     : False
PSComputerName        : 
CimClass              : Root/Microsoft/Windows/TaskScheduler:MSFT_TaskRepetitionPattern
CimInstanceProperties : {Duration, Interval, StopAtDurationEnd}
CimSystemProperties   : Microsoft.Management.In




# Modify the trigger repetition settings, which cannot be done via the native cmdlet
$Task.Triggers.Repetition.Duration = 'P1D'
$Task.Triggers.Repetition.Interval = 'PT60M'
$Task | Set-ScheduledTask -User $env:USERNAME

TaskPath   TaskName   State
--------   --------   -----
\          TestTask   Ready



# View the change
$Task.Triggers.Repetition | Format-List * -Force

Duration              : P1D
Interval              : PT60M
StopAtDurationEnd     : False
PSComputerName        : 
CimClass              : Root/Microsoft/Windows/TaskScheduler:MSFT_TaskRepetitionPattern
CimInstanceProperties : {Duration, Interval, StopAtDurationEnd}
CimSystemProperties   : Microsoft.Management.Infrastructure.CimSystemProperties

Modify the XML file directly - say the repetition times settings using a simple replace, to something else

(Get-Content -Path 'C:\Windows\System32\Tasks\TestTask').Replace('P1D','P12H') | 
Set-Content -Path 'C:\Windows\System32\Tasks\TestTask'

Did you omit the -password parameter when setting the scheduled task?

`Register-ScheduledTask -TaskName “Check Windows Updates” -Trigger $Trigger -User $User -Password $password -Action $Action -RunLevel Highest -Force`

I have also used, Security Principals for tasks running as a network service or similar.

$taskPath = ""
$taskName = “Test Run Task”
$program = “C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe”
$arguments = “-command $scriptPath\test.ps1”
$a = New-ScheduledTaskAction -Execute $program -Argument $arguments
$t = New-ScheduledTaskTrigger -Daily -At 12am
$p = New-ScheduledTaskPrincipal -UserID “NetworkService” -LogonType ServiceAccount -RunLevel Highest
$s = New-ScheduledTaskSettingsSet
$d = New-ScheduledTask -Action $A -Principal $p -Trigger $T -Settings $S
$task = Register-ScheduledTask -InputObject $d -TaskPath $taskPath -TaskName $taskName

This would run as networkservice in an elevated manner, New-ScheduledTaskPrincipal (ScheduledTasks) | Microsoft Docs

For the other point, about running at 2012 level that would be

$s = New-ScheduledTaskSettingsSet -compatibility Win8