My .bat file looks like this:
@echo off
CD /D "%~dp0"
if [%2]==[] (
set user=%USERNAME%
) else (
set user=%2%
)
:getFile
if [%1]==[] (
set /p file=Enter file name :
) else (
set file=%~f1
echo File name: %~f1
)
:checkFile
for /f "useback tokens=*" %%a in ('%file%') do set file=%%~a
if not exist "%file%" (
echo Error: Could not find file: %file%
echo.
)
:: Check for admin permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' == '0' (
goto gotAdmin
)
:: Rerun this batch with admin rights
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "cmd", "/c """"%~f0"" ""%file%"" ""%user%""""", "%CD%", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
exit /B
:gotAdmin
if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
pushd "%CD%"
CD /D "%~dp0"
echo.
:eof
pause
exit /B
I have these two test files:
- C:\Test\Folder\ファイル.txt
- C:\Test\フォルダ\File.txt
When I run the batch file above and drag 1 onto the cmd window I get:
, which is good.
When I do the same for 2, I get:
When I call UAC.ShellExecute, %file% isn't passed correctly.
How can I get around this problem?
My preferred way of starting a batch file with administrator permissions is to create a shortcut, and then mark that shortcut as requiring administrator permissions.
First right-click foo.bat, then create a shortcut. Open the properties for that shortcut, click the Advanced… button and enable Run as administrator.
This has a downside: you can't drag file names onto the resulting command prompt window. But you can drag a file onto the shortcut.
But what if I don't want or can't use a shortcut?
You can avoid the need to write arbitrary Unicode characters to the file by passing your file name as an argument to your script. Even if the VBS file is in ANSI encoding, the script host always uses Unicode internally.
So here is how you write the VBS file and run it: