windowspowershellbatch-fileshutdownmmc

How to run script with elevated privileges on Shutdown using gpedit.msc on Windows 11?


I can't run a bat file on Shutdown on Windows 11.

runAs.bat:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown\changeComputerName.ps1""' -Verb RunAs}"

changeComputerName.ps1:

$computerName = -join ((97..122) | Get-Random -Count 15 | ForEach-Object {[char]$_})
Rename-Computer $computerName

They are both located in:

C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown\

The Shutdown properties is set to run the runAs.bat file which in turn runs a PowerShell process with elevated privileges to change the computer name.

When running the bat file from the terminal, it asks for elevated privileges and then it runs successfully.

Where should I be looking for error/debug info?

Thanks


Solution

  • I was able to get passed this UAC(https://learn.microsoft.com/en-us/windows/security/application-security/application-control/user-account-control/how-it-works) limitation by creating a Scheduled Task which runs the .bat file with "Run with highest privileges" checked in the General Tab. The script runs on every logon of every user to the machine.

    I also disabled UAC at the beginning and renabled it at the end of my powershell script. By using this PowerShell line:

    Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -Value 0