powershellbatch-fileelevated-privileges

Bat File fails to start powershell script without hard-coded directory


My plan is as follows:

  1. Open .bat file
  2. File then opens a PS window with script execution allowed and as admin(!)
  3. Directory must be variable for it to run on any PC in that folder.
  4. Install Chocolatey and Winget for it to install apps.
  5. Must be without user input.

My .ps1 File is named Start.ps1 and the batch file is named Start.bat.

In the current batch configuration, it won't execute the PS window as admin, or with script execution allowed.

PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""C:\Users\user\Desktop\Install\StartNew.ps1""' -Verb RunAs}"

It does work when directory is 1:1, but on different machine it doesn't start the install of chocolatey and winget.


Solution

  • @echo off & setlocal
    
    :: Determine the full path to the companion .ps1 file (Start.ps1)
    :: based on the full path of this batch file (Start.bat)
    set "PS1File=%~dpn0.ps1"
    
    :: Now reference %PS1File% as part of the PowerShell command.
    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -Verb RunAs PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File \"%PS1File%\"'"
    

    Note: