<# .SYNOPSIS Create a daily scheduled task in Windows Task Scheduler for running PowerShell scripts in a user's context (hopefully a service account) .EXAMPLE Create-ScheduledTaskForPowerShell -timeOfDay 15:00 -pathToScript "C:\Backups\Backup-ToAzureBlob.ps1" -directoryOfTheScript "C:\Backups" ` -userName "Lappy\TestUser" -nameOfScheduledTask "BackupToAzure" .INPUTS [DateTime]$timeOfDay - A time of the day when the scheduled task should run; it accepts AM/PM times or 24 clock times (use the 24 hour clock you savages!) [String]$pathToScript - the full path to the script including the script's file name [String]$directoryOfTheScript - The path where certificate will be exported to as a .cer file; no trailing backslash needed e.g. ("C:\Backups") [String]$userName - The name of the user who will run the script (hopefully a service account, whether local or domain include the FQDN e.g. domainName\userName or serverName\userName [String]$nameOfScheduledTask - The name of the scheduled task .OUTPUTS A scheduled task in Windows Task Scheduler #> Function Create-ScheduledTaskForPowerShell { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [DateTime]$timeOfDay, [Parameter(Mandatory = $true)] [String]$pathToScript, [Parameter(Mandatory = $true)] [String]$directoryOfTheScript, [Parameter(Mandatory = $true)] [String]$userName, [Parameter(Mandatory = $true)] [String]$nameOfScheduledTask ) $taskTrigger = New-ScheduledTaskTrigger -Daily -At 15:00 #Use the 24 hour clock here you savages! $taskAction = New-ScheduledTaskAction -Execute "PowerShell" -Argument "-NoProfile -ExecutionPolicy Bypass -File '$pathToScript' -Output 'HTML'" -WorkingDirectory $directoryOfTheScript $Settings = New-ScheduledTaskSettingsSet -DontStopOnIdleEnd -RestartInterval (New-TimeSpan -Minutes 1) -RestartCount 10 -StartWhenAvailable $Settings.ExecutionTimeLimit = "PT0S" $SecurePassword = $password = Read-Host -AsSecureString $Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $userName, $SecurePassword $Password = $Credentials.GetNetworkCredential().Password Register-ScheduledTask $nameOfScheduledTask -Settings $Settings -Action $taskAction -Trigger $taskTrigger -User $UserName -Password $Password -RunLevel Highest } Create-ScheduledTaskForPowerShell -timeOfDay 15:00 -pathToScript "C:\Backups\Backup-ToAzureBlob.ps1" -directoryOfTheScript "C:\Backups" -userName "Lappy\TestUser" -nameOfScheduledTask "BackupToAzure"