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 #http://blogs.technet.com/b/heyscriptingguy/archive/2015/01/13/use-powershell-to-create-scheduled-tasks.aspx $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 #http://blogs.technet.com/b/heyscriptingguy/archive/2015/01/14/use-powershell-to-configure-scheduled-task.aspx $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