Search code examples
powershellbatch-fileargumentselevated-privileges

Run Powershell with parameters from batch file


For convenience of use, I need to put my powershell script in a bat file. The bat file content is as follows:

# 2>NUL & @CLS & PUSHD "%~dp0" & powershell -COMMAND "Start-Process powershell -Verb RunAs -ArgumentList '-windowstyle hidden -nol -nop -ep bypass ""[IO.File]::ReadAllText(''%~f0'')|iex""'"
# powershell script

However, in the powershell script, I need to get the path of the bat file. I know I can get the full path by 'SET "batFilePath=%~f0"'... but I don't know what I should do next to be able to pass in and use the batFilePath argument in the powershell script. Please help me, thank you very much.

P/s: It's not that I'm lazy, I tried looking for similar topics, but the answers are all very confusing to me, I'm not sure what to do in my case. Excuse me.


Solution

  • If you run 'SET "batFilePath=%~f0"' in cmd you can access the var in powershell by running '$env:batFilePath'.

    Here is an example code

    # 2>NUL & @CLS & SET "batFilePath=%~f0" & powershell -Command "Start-Process powershell -Verb RunAs -ArgumentList ""-windowstyle hidden -nol -nop  Invoke-Expression (Get-Content -Path $env:batFilePath -Raw)"""
    

    Update: To pass $batFilePath to the now PowerShell process you can use this code

    # 2>NUL & @CLS & SET "batFilePath=%~f0" & powershell -Command "Start-Process powershell -Verb RunAs -ArgumentList \"-NoLogo -NoProfile -Command `$batFilePath='$env:batFilePath'; Invoke-Expression (Get-Content -Path $env:batFilePath -Raw)\"" & exit
    

    Actually you don't need to set 'batFilePath' in cmd you can simply use '~f0' like this

    # 2>NUL & @CLS & powershell -Command "Start-Process powershell -Verb RunAs -ArgumentList \"-NoLogo -NoProfile -Command `$batFilePath='%~f0'; Invoke-Expression (Get-Content -Path %~f0 -Raw)\"" & exit