Search code examples
powershellbatch-fileuac

Create Batch File to enable PS script exec and launch elevated PS shell with line commands


To simplify my job of finding every installer and manually launching them one by one, I would like to make a .bat file that runs a chocolatey install for ~10 app-installers without doing something in the meantime.

I tried to use the -command option for entering my command, but it never executed it in a elevated window of PowerShell.

  • start bat file --> starts elev PS shell.
  • run PS script on Desktop as Admin --> install chocolatey programs.

My code that I would like to run in a elevated PS shell:

Set-ExecutionPolicy Bypass -scope Process -Force
Write-Host -ForegroundColor Black -BackgroundColor White "Chocolatey wird heruntergeladen und installiert"
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
choco feature enable -n=allowGlobalConfirmation
Write-Host -ForegroundColor Black -BackgroundColor White "Programme werden heruntergeladen und installiert"
choco install googlechrome
choco install firefox
choco install irfanview
choco install mpc-hc-clsid2
choco install 7zip
choco install notepadplusplus.install
choco install vlc
choco install adobereader
choco install libreoffice-still

Ideally I just have to click on the .bat file and accept UAC for the admin window of PS and all programs are downloaded and installed in the background.

powershell -Command "&{ Start-Process powershell -ArgumentList '-File C:\users\gabri\desktop\start.ps1' -Verb RunAs}"

The .bat file only shows a UAC, and then nothing happens.


Solution

  • Putting Set-ExecutionPolicy Bypass -scope Process -Force inside a script file (*.ps1) somewhat defeats the purpose, because if the persistently configured execution policy prevents execution of your script to begin with, your attempt at a process-level override never gets to execute.

    Instead, use the PowerShell CLI's -ExecutionPolicy parameter for a process-level override of the execution policy.

    Additionally, you may want to use the -NoExit CLI parameter so as to keep the elevated session open, which allows you to inspect the results.

    :: From a batch file.
    powershell -Command "Start-Process -Verb RunAs powershell -ArgumentList '-ExecutionPolicy Bypass -NoExit -File C:\users\gabri\desktop\start.ps1'"