Powershell – Create a Scheduled Task Using a Domain User as the Account

This script creates  a scheduled task running with elevated privileges, using a Domain User as the account  to run under.

One of my tasks is to install a  web based product using powershell. Part of that install is to schedule a powershell script to archive and prune logs. The script below will create a Scheduled task called CWS-ArchiveLogFiles, which will run on a daily basis as 12am and run a powershell script in C:\ScheduledTasks called CWS-ArchiveLogFiles.ps1.

It is based on a couple of “Scripting Guy” blogs (referenced in the code below)

basically if you want to assign a user and password to a scheduled task , this is the way vs “network service” or “builtin\administators”

#Create a directory to put the powershell script in
new-item -path c:\ -name ScheduledTasks -itemtype directory -force

#Copy the file from Source to Destination
Copy-Item -path "c:\temp\ArchiveLogFiles.ps1" -Destination "C:\ScheduledTasks\ArchiveLogFiles.ps1" -force

#Create the Action
$action = New-ScheduledTaskAction -Execute 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -Argument "C:\ScheduledTasks\ArchiveLogFiles.ps1"

#Create a trigger - e.g. when do you wan it to run
$trigger =  New-ScheduledTaskTrigger -Daily -At 12am
#When the task is created, run with elevated privilages using the builtin administrators group

#Modify task to set compatibility to Win8 aka 2012 / 2012 R2
$settings = New-ScheduledTaskSettingsSet -Compatibility Win8

#Now we "splat" the parameters to the Register-ScheduledTask cmdlet
# we could do 
#Register-ScheduledTask -TaskName "ArchiveLogFiles" -Action $action -Trigger $trigger -User $Username -Password $Password -Settings $settings -RunLevel "Highest" -Description "Archives Log files"
# but that looks ugly and hard to read on one line
$params = @{
"TaskName"    = "ArchiveLogFiles"
"Action"      = $action
"Trigger"     = $trigger
"User"        = $Username
"Password"    = $Password
"Settings"    = $settings
"RunLevel"    = "Highest"
"Description" =  "Archives Log files"

Register-ScheduledTask @Params

Note: For passing parameters to the script




Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.