August 24, 2015

PowerShell - How to Register, Start and Unregister a ScheduledJob

In Windows PowerShell 3.0, Job Scheduling cmdlets are available in the PSScheduledJob module, which let you run commands asynchronously in the background. This allows you to continue running commands at the command line while the background job runs. 

For the scope of this post, I will demonstrate how to register a scheduled job, start and then unregister it.

Register Scheduled Job:
$triggerTimerJob1 = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -minute 1) -RepetitionDuration ([TimeSpan]::MaxValue)

Register-ScheduledJob -Name TimerJob1 -Trigger $triggerTimerJob1 -ScriptBlock {
    Get-Date | Out-File -FilePath "C:\Test\myfile.txt" -Append
}

The variable $triggerTimerJob1 is the trigger we need to define how often our job will be executed. For exmaple, I specified it as Once with starting time as current time. Other valid values for this parameter are : AtLogon, AtStartup, Daily, Weekly.
-RepetitionDuration specifies how long the repetition pattern repeats after the task starts.
-RepetitionInterval Specifies an amount of time between each restart of the task. The task will run, wait for the time interval specified, and then run again. For the demo purpose I used 1 minute.

Register-ScheduledJob is the cmdlet to register job. We define the job name in the -Name parameter, and tirgger with our defined variable.
The -ScriptBlock parameter is the actual job script which we want to execute. Here I simply put the current Date in a text file with -append parameter, so we could test the the file how often the job is actually executed.

Start Scheduled Job:
Start-Job -DefinitionName TimerJob1

Start-Job cmdlet is the command used to start job. We need to place our same job name here in DefinitionName parameter.

Unregister Scheduled Job:
To Unregister a job we use the Unregister cmdlet with job name:
UnRegister-ScheduledJob -Name TimerJob1

References: https://technet.microsoft.com/en-us/library/jj649821%28v=wps.630%29.aspx

No comments:

Post a Comment