Register-ScheduledJob (PowerShell 3.0+)

Create a new scheduled job.

Syntax
      Register-ScheduledJob [-Name] String [-ScriptBlock] ScriptBlock [-ArgumentList Object[]]
         [-Authentication AuthenticationMechanism] [-Credential PSCredential]
            [-InitializationScript ScriptBlock] [-MaxResultCount Int32]
               [-RunAs32] [-RunNow] [-ScheduledJobOption ScheduledJobOptions]
                  [-Trigger ScheduledJobTrigger[]] [-Confirm] [-WhatIf] [CommonParameters]
 
      Register-ScheduledJob [-Name] String [-FilePath] String [-ArgumentList Object[]]
         [-Authentication AuthenticationMechanism] [-Credential PSCredential]
            [-InitializationScript ScriptBlock] [-MaxResultCount Int32]
               [-RunAs32] [-RunNow] [-ScheduledJobOption ScheduledJobOptions]
                  [-TriggerScheduledJobTrigger[]] [-Confirm] [-WhatIf] [CommonParameters]

Key
   -ArgumentList Object[]
        Values for the parameters of the script that is specified by the -FilePath parameter or for the 
        command that is specified by the -ScriptBlock parameter.

    -Authentication AuthenticationMechanism
        The mechanism that is used to authenticate the user’s credentials.   
        Valid values are Default, Basic, Credssp, Digest, Kerberos, Negotiate, and NegotiateWithImplicitCredential.
        The default value is Default. For more see AuthenticationMechanism enumeration.

        CAUTION: Credential Security Service Provider (CredSSP) authentication, in which the user’s credentials are 
        passed to a remote computer to be authenticated, is designed for commands that require authentication on more 
        than one resource, such as accessing a remote network share. This mechanism increases the security risk of the 
        remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to 
        control the network session.

    -Credential PSCredential
        Specifies a user account that has permission to run the scheduled job. The default is the current user.

        Type a user name, such as "User64" or "Domain64\User64", or enter a PSCredential object, such as one from 
        Get-Credential. If you enter only a user name, you will be prompted for a password.

    -FilePath String
        A script that the scheduled job will run. Enter the path to a .ps1 file on the local computer. 
        To specify default values for the script parameters, use the -ArgumentList parameter.
        Every Register-ScheduledJob command must use either the -ScriptBlock or -FilePath parameters.

    -InitializationScript ScriptBlock
        The fully qualified path to a PowerShell script (.ps1). The initialization script runs in the session 
        that is created for the background job before the commands that are specified by the -ScriptBlock 
        parameter or the script that is specified by the -FilePath parameter . Use the initialization script to 
        configure the session, such as adding files, functions, or aliases, creating directories, or checking for 
        prerequisites.

        To specify a script that runs the primary job commands, use the -FilePath parameter.

        If the initialization script generates an error (even a non-terminating error), the current instance of the 
        scheduled job does not run and its status is "Failed."

    -MaxResultCount Int32
        Specifies how many job result entries are maintained for the scheduled job. The default value is 32.

        PowerShell saves the execution history and results of each triggered instance of the scheduled job on 
        disk. The value of this parameter determines the number of job instance results that are saved for this 
        scheduled job. When the number of job instance results exceeds this value, PowerShell deletes the 
        results of the oldest job instance to make room for the results of the newest job instance.

        The job execution history and job results are saved in the 
        $home\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs\JobName\Output\Timestamp directories on the 
        computer on which the job is created.
        To see the execution history, use Get-Job. To get the job results, use Receive-Job.

        The -MaxResultCount parameter sets the value of the ExecutionHistoryLength property of the scheduled job.

        To delete the current execution history and job results, use the -ClearExecutionHistory parameter 
        of Set-ScheduledJob.

    -Name String
        A name for the scheduled job.
        The name is also used for all started instances of the scheduled job. 
        The name must be unique on the computer. This parameter is mandatory.

    -RunAs32
        Run the scheduled job in a 32-bit process.

    -ScheduledJobOption ScheduledJobOptions
        Sets options for the scheduled job. Enter a ScheduledJobOptions object, such as one that you create   
        using New-ScheduledJobOption, or a hash table value.

        You can set options for a scheduled job when you register the schedule job or use Set-ScheduledJobOption 
        or Set-ScheduledJob to change the options.

        Many of the options and their default values determine whether and when a scheduled job runs. Be sure to 
        review these options before scheduling a job. For a description of the scheduled job options, including the 
        default values, see New-ScheduledJobOption.

        To submit a hash table, use the following keys. In the following hash table, the keys are shown with their 
        default values.

        @{StartIfOnBattery=$False; StopIfGoingOnBattery=$True; WakeToRun=$False; StartIfNotIdle=$False; 
        IdleDuration="00:10:00"; IdleTimeout="01:00:00"; StopIfGoingOffIdle=$True; RestartOnIdleResume=$False; 
        ShowInTaskScheduler=$True; RunElevated=$False; RunWithoutNetwork=$False; DoNotAllowDemandStart=$False; 
        MultipleInstancePolicy=IgnoreNew}

    -ScriptBlock ScriptBlock
        Specifies the commands that the scheduled job runs. Enclose the commands in braces ( { } ) to create a script 
        block. To specify default values for command parameters, use the -ArgumentList parameter.

        Every Register-ScheduledJob command must use either the ScriptBlock or FilePath parameters.

    -Trigger ScheduledJobTrigger[]
        Specifies the triggers for the scheduled job. Enter one or more ScheduledJobTrigger objects, such as the 
        objects that New-JobTrigger returns, or a hash table of job trigger keys and values.

        A "job trigger" starts the schedule job. The trigger can specify a one-time or recurring scheduled or an 
        event, such as when a user logs on or Windows starts.

        The Trigger parameter is optional. You can add a trigger when you create the scheduled job,  use 
        Add-JobTrigger, Set-JobTrigger, or Set-ScheduledJob to add or change job triggers later, or use 
        Start-Job to start the scheduled job immediately. You can also create and maintain a scheduled job 
        without a trigger that is used as a template.

        To submit a hash table, use the following keys.

        @{Frequency="Once" (or Daily, Weekly, AtStartup, AtLogon);At="3am" (or any valid time string);
        DaysOfWeek="Monday", "Wednesday" (or any combination of day names);
        Interval=2 (or any valid frequency interval);
        RandomDelay="30minutes" (or any valid timespan string);
        User="Domain1\User01 (or any valid user; used only with the AtLogon frequency value)
        }

    -RunNow
        Start a job immediately, as soon as the Register-ScheduledJob cmdlet is run. This parameter eliminates the 
        need to trigger Task Scheduler to run a PowerShell script immediately after registration, and does not 
        require users to create a trigger that specifies a starting date and time.

   -Confirm
       Prompt for confirmation before running the cmdlet.

   -WhatIf
       Show what would happen if the cmdlet runs. The cmdlet is not run.

A "scheduled job" is a PowerShell background job that can be started automatically on a one-time or recurring schedule. Scheduled jobs are stored on disk and registered in Task Scheduler, so they can be managed in Task Scheduler or by using the Scheduled Job cmdlets.

When a scheduled job starts, it creates an "instance" of the scheduled job. Scheduled job instances are identical to PowerShell background jobs, except that the results are saved on disk. Use the Job cmdlets, such as Start-Job, Get-Job, and Receive-Job to start, view, and get the results of the job instances.

Use Register-ScheduledJob to create a new scheduled job. To specify the commands that the scheduled job runs, use the -ScriptBlock parameter; to specify a script that the job runs, use the -FilePath parameter.

PowerShell scheduled jobs use the same job triggers and job options that Task Scheduler uses for scheduled tasks.

The -Trigger parameter of Register-ScheduledJob adds one or more job triggers that start the job. The Trigger parameter is optional, so you can add triggers when you create the scheduled job, add job triggers later, add the RunNow parameter to start the job immediately, use the Start-Job cmdlet to start the job immediately at any time, or save the untriggered scheduled job as a template for other jobs.

The -Options parameter lets you customize the options settings for the scheduled job. The -Options parameter is also optional, so you can set job options when you create the scheduled job or change them at any time.
Many job option settings have the capacity to prevent the scheduled job from running.

Examples

Create a scheduled job that searches the $home directory for .ps1 files and copies them to a file share:

PS C:\> Register-ScheduledJob –Name Archive-Scripts -ScriptBlock { dir $home\*.ps1 -Recurse | Copy-Item -Destination \\Server64\Share\Archive }

Create a scheduled job with a trigger and custom options:

PS C:\> $opt = New-ScheduledJobOption –WakeToRun –StartIfNotIdle –MultipleInstancesPolicy Queue
PS C:\> $trig = New-JobTrigger -Weekly -At "23:00" -DaysOfWeek Monday –WeeksInterval 2
PS C:\> Register-ScheduledJob –Name UpdateVersion –FilePath \\Server64\Scripts\UpdateVersion.ps1 –Trigger $trig –ScheduledJobOption $opt

Create scheduled jobs on the computers listed in Servers.txt The command uses Invoke-Command to run a Register-ScheduleJob command on each remote computer:

PS C:\> Invoke-Command -ComputerName (Get-Content Servers.txt) –ScriptBlock {Register-ScheduledJob -Name SS64 -FilePath "\\Server64\Scripts\SS64.ps1" -ScheduledJobOption $opt –Trigger $trig } -Credential $cred

“New York is an exciting town where something is happening all the time, most unsolved” ~ Johnny Carson

Related PowerShell Cmdlets

Scheduler cmdlets - Get/Set scheduled jobs.
Disable-ScheduledJob - Disable a scheduled job.
Get-ScheduledJob - Get scheduled jobs on the local computer.


 
Copyright © 1999-2024 SS64.com
Some rights reserved