I have following lines in my Batch script which in turn calls Powershell command to self-elevate the batch file as Admin.
@echo off && setlocal
if not "%1"=="admin" (powershell start -verb runas '%0' admin & pause & exit /b)
....
....
But the Batch file path itself and as result the '%0' contains spaces in the %USERNAME%(Vivek Shah) especially, and that's why when invoking this script, it throws error:
The term 'C:\Users\Vivek' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1
How do I handle spaces in '%0' and make this script working perfectly ??
Already tried '%~0' & '"%0"' but both apparently don't work.
Use
%~f0to refer to the running batch file's full path.cmd /c call /?for an explanation of the syntax.To ensure that this path is passed as-is to PowerShell's
Start-Process(whose built-in aliases arestartandsaps), enclose it in\"..."\(the\-escaping is necessary in order for the (implied)-Commandargument passed topowershell.exe, the Windows PowerShell CLI, to pass the"characters through as part of the command to execute).[1][1] Note: Without enclosing the implied
-Commandargument in"..."overall means that the value of~%f0is subject to whitespace normalization, meaning that runs of multiple whitespace characters are folded into a single space each. However, that is rarely a problem in practice. Just adding an overall"..."enclosure (powershell "start ..." & pause & exit /b) is not necessarily enough, unfortunately, because it requires individually^-escaping anycmd.exemetacharacters inside\"...\". In the rare event that whitespace normalization is a problem, withpowershell.exeyou can use"^""..."^""(sic) inside overall"...", but only outsidefor /floops - see this answer. Fortunately, in PowerShell (Core) 7+, whose CLI ispwsh.exe, the robust solution is simpler: both outside and insidefor /f, use overall"..."enclosure with embedded""...""quoting.