重新运行时将Unicode参数传递给Windows .bat文件 [英] Passing Unicode parameters to Windows .bat file when rerunning it

查看:97
本文介绍了重新运行时将Unicode参数传递给Windows .bat文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的.bat文件如下:

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:

  1. C:\ Test \ Folder \ファイル.txt
  2. C:\ Test \フォルダ\ File.txt

当我运行上面的批处理文件并将1拖到cmd窗口时,我得到:

When I run the batch file above and drag 1 onto the cmd window I get:

,很好.

当我对2做同样的操作时,我得到:

When I do the same for 2, I get:

当我调用UAC.ShellExecute时,%file%未正确传递.

When I call UAC.ShellExecute, %file% isn't passed correctly.

如何解决这个问题?

推荐答案

启动具有管理员权限的批处理文件的首选方法是创建快捷方式,然后将该快捷方式标记为需要管理员权限.

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.

首先右键单击foo.bat,然后创建一个快捷方式.打开该快捷方式的属性,单击高级…按钮并启用以管理员身份运行.

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.

但是,如果我不想或不能使用快捷方式怎么办?

通过将文件名作为参数传递给脚本,可以避免向文件写入任意Unicode字符的麻烦.即使VBS文件采用ANSI编码,脚本主机也始终在内部使用Unicode.

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.

因此,这是编写和运行VBS文件的方式:

So here is how you write the VBS file and run it:

:: Rerun this batch with admin rights
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "cmd", "/c """"%~f0"" """ + Wscript.Arguments.Item(0) + """ ""%user%""""", "%CD%", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs" "%file%"
exit /B

这篇关于重新运行时将Unicode参数传递给Windows .bat文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆