I'm trying to create bat script that can start PowerShell script named the same as bat file in proper working directotry.
This is what I got:
@ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -WorkingDirectory '%~dp0' -Verb RunAs}"
PAUSE
Passing working directory this way does not work.
How to make script that will pass proper working directroy and also command line arguments?
A workaround is to let the PowerShell script change the directory to it's own origin with:
as the first command.
As per mklement0s hint: In PSv3+ use the simpler:
Or use this directory to open adjacent files.
The
-WorkingDirectory
parameter doesn't work when using-Verb RunAs
. Instead, you have to set the working directory by callingcd
within a-Command
string.This is what I use: (cmd/batch-file command)
If you want to make a "Run script as admin" right-click command in Windows Explorer, create a new registry key at
HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command
, and set its value to the command above -- except replacing%cd%
with%W
, andPathToPS1File
with%1
(if you want it to execute the right-clicked file).Result: (Windows Explorer context-menu shell command)
EDIT: There's an alternative way to have the script be run as admin from Explorer, by using the "runas" sub-key: https://winaero.com/blog/run-as-administrator-context-menu-for-power-shell-ps1-files
If you want to run your script as admin from an existing powershell, remove the outer powershell call, replace
%W
with$pwd
, replace%1
with the ps1 file-path, and replace each\""
with just"
.Result: (PowerShell command)