I am currently trying to run the command cup all -y
with task scheduler in windows, which basically updates all the packages installed by Chocolatey package installer.
I have scheduled the task to run whenever I login to the computer, PowerShell window pops up for a brief second and goes away, and then nothing happens.
I am not sure if the command is being executed and the packages are getting updated.
Kindly help me with this.
I have tried to change the path to system32 to make it run with administrative privileges using the following command:
Set-Location -Path C:\Windows\system32
Also tried clicking on "Run with highest privileges" in task scheduler while creating a task, that didn't work as well.
To run as scheduled task as yourself, interactively, but with elevation (administrative privileges), define the user context with New-ScheduledTaskPrincipal
with -RunLevel Highest
as follows, to be passed to Register-ScheduledTask
's -Principal
parameter later:
# NOTE: Setting up a scheduled task this way requires
# running from an ELEVATED session too.
# -LogonType Interactive is implied.
# Pass the result to Register-ScheduledTask -Principal.
New-ScheduledTaskPrincipal -RunLevel Highest -UserID $env:USERNAME
Note:
This assumes that your user account is an administrator account.
For troubleshooting, you can place a pause
statement at the end of your script, so you'll see what happens during execution of the script as a scheduled task.
Alternatively, invoke the script with the -NoExit
PowerShell CLI parameter, which keeps the PowerShell session alive after executing the script, but for security reasons you should only do that during troubleshooting.
Here's a complete example, which sets up a task to run interactively, with elevation, whenever you log on.
It uses a sample PowerShell command that simply displays a message and waits for the user to press Enter to close the window again. Replace
-Command "'Hi from the scheduled task running with elevation'; pause"
with something like
-File C:\path\to\your\Script.ps1
#requires -RunAsAdministrator
# == The command (program) to run.
$action = New-ScheduledTaskAction -Execute powershell -Argument @'
-NoProfile -Command "'Hi from the scheduled task running with elevation'; pause"
'@
# == Run as yourself, interactively, with elevation.
$user = New-ScheduledTaskPrincipal -UserID $env:USERNAME -RunLevel Highest
# == Run on your every logon
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
# == Register the task with name '_Test'
New-ScheduledTask -Action $action -Principal $user -Trigger $trigger |
Register-ScheduledTask '_Test' -Force
# Command to later remove the task again:
# Unregister-ScheduledTask -ErrorAction Ignore -TaskName _Test -Confirm:$false