CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Creating Scheduled Tasks That Run PowerShell Scripts with Elevated Privileges

👀 Views: 318 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-24
powershell scheduled-tasks elevated-privileges PowerShell

I'm writing unit tests and After trying multiple solutions online, I still can't figure this out. I'm having trouble creating a scheduled task in PowerShell 7.3 that runs a script with elevated privileges. I've used the `New-ScheduledTask` cmdlet to create the task, but it seems like it's not running with the necessary permissions. Here's the code I've been using: ```powershell $action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-File "C:\Scripts\MyScript.ps1"' $trigger = New-ScheduledTaskTrigger -AtStartup $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount Register-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -TaskName 'MyPowerShellTask' -Description 'Runs PowerShell script at startup' ``` When I check the task in Task Scheduler, it shows that it runs under the SYSTEM account, but the script does not execute as expected. I even tried running the task manually, and I received the following behavior message: ``` The task is configured to run only if the following security conditions are met: The user is logged on. ``` I've also attempted to set the `-AllowStartIfOnBatteries` and `-DontStopIfGoingOnBatteries` parameters, but those don't seem to affect the permissions scenario. I need this task to run regardless of the user session state. Has anyone encountered this scenario before, or can someone suggest a workaround to ensure the script runs with elevated permissions correctly? This is for a microservice running on macOS. Any examples would be super helpful. What are your experiences with this?