Skip to content

Instantly share code, notes, and snippets.

@brynsp
Last active May 24, 2017 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brynsp/1c46c6b6b0e5165c7ca31188af5ca629 to your computer and use it in GitHub Desktop.
Save brynsp/1c46c6b6b0e5165c7ca31188af5ca629 to your computer and use it in GitHub Desktop.
PowerShell function to create a scheduled task to run a powershell script
[CmdletBinding()]
param
(
# The security principal used to execute the task
[Parameter(Mandatory,
Position = 0,
HelpMessage = 'Supply a username'
)]
[string]
$UserName,
# The Active Directory domain of the user account
[Parameter(Mandatory,
Position = 1,
HelpMessage = 'Supply the domain name of the user account')]
[string]
$Domain,
# Specifies a path to one or more locations.
[Parameter(Mandatory,
Position = 2,
HelpMessage = "Path to the powershell script to be executed in the task.")]
[Alias("PSPath")]
[ValidateNotNullOrEmpty()]
[ValidateScript(
{
foreach ( $p in $_ )
{
if (-not (Test-Path -Path $p -PathType Leaf))
{
throw "$p is not a file or does not exist"
}
}
Write-Output $true
})]
[string]
$Path
)
$creds = Get-Credential -UserName "$Domain\$UserName" -Message 'Enter the password for the account used to run the task.'
$actionParams = @{
Argument = '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -Command "& {0}{1}{2}"' -f '{', $Path, '}'
Execute = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
}
$action = New-ScheduledTaskAction @actionParams
$principalParams = @{
LogonType = 'Password'
RunLevel = 'Highest'
UserId = $UserName
}
$principal = New-ScheduledTaskPrincipal @principalParams
$triggerParams = @{
At = (Get-Date -Hour 0 -Minute 0 -Second 0)
Once = $true
RepetitionDuration = ([timespan]::MaxValue)
RepetitionInterval = (New-TimeSpan -Minutes 1)
}
$trigger = New-ScheduledTaskTrigger @triggerParams
$settingsParams = @{
ExecutionTimeLimit = (New-TimeSpan -Minutes 0)
RestartInterval = (New-TimeSpan -Minutes 1)
RestartCount = 5
StartWhenAvailable = $true
}
$settings = New-ScheduledTaskSettingsSet @settingsParams
$taskParams = @{
Action = $Action
Description = 'Invokes a PowerShell script that starts the [REDACTED] process.'
Principal = $principal
Settings = $settings
Trigger = $trigger
}
$task = New-ScheduledTask @taskParams
$taskRegisterParams = @{
InputObject = $task
Password = $creds.GetNetworkCredential().Password
TaskName = 'Company Task 1'
TaskPath = '\CompanyTasks'
User = $creds.UserName
}
Register-ScheduledTask @taskRegisterParams
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment