我需要使用包含特殊字符(变音符号)的特殊 URL 打开浏览器。例如 URL 中的“è”:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "https://google.com/search?q=Mèxico"
我可以使用 urlencode,例如“https://google.com/search?q=M%C3%A8xico”,但是否可以不进行转义,因为是用户生成了 bat。类似 @this_bat_uses_utf8 之类的东西。谢谢。
以下代码返回空字符串:
@echo off
setlocal
set "string=Trois-Rivières, QC"
:: Define simple macros to support JavaScript within batch
set "beginJS=mshta "javascript:code(close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write("
set "endJS=)));""
:: FOR /F does not need pipe
for /f "tokens=" %%N in (
'%beginJS% encodeURIComponent("%string%") %endJS%'
) do set encoded=%%N
echo %string% -^> %encoded%
示例 2:这不起作用,删除 è 它将开始工作
setlocal
chcp 65001 >nul
"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe" --app="https://google.com/search?q=Trois-Rivières,QC"
答案1
批处理没有这样的指令。
您最多可以使用chcp 65001
UTF-8 并在前面添加
UTF-8 字节序
到.bat
文件。
urlencode
对于批量 实现,请参见StackOverflow 答案:
@echo off
setlocal
setlocal
set "string=Trois-Rivières, QC"
:: Define simple macros to support JavaScript within batch
set "beginJS=mshta "javascript:code(close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write("
set "endJS=)));""
:: FOR /F does not need pipe
for /f "usebackq" %%N in (
`%beginJS% encodeURIComponent('%string%') %endJS%`
) do set "encoded=%%N"
echo %string% -^> %encoded%
答案2
您可以编写一个批处理文件,直接运行您的代码,无需任何第三方工具。
将此代码存储在以无 BOM 的 UTF8 编码的批处理文件中(如果有 BOM,则顶部应该有一个空行)。
@echo off
setlocal
REM remeber the current code page
for /f "tokens=3 delims=:. " %%d in ('chcp') do set "_OLD_CP_=%%d"
REM set the code page to UTF8
chcp 65001 >nul
REM do the actual work (remove the 'start ""' if you want to wait for the end of the task)
start "" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "https://google.com/search?q=Mèxico"
REM restore the old code page (if needed)
chcp %_OLD_CP_% >nul
答案3
@echo off
>nul chcp 65001 & color
for /f delims^= %%i in ('
powershell -nOp -c """$([uri]::EscapeDataString('Mèxico'))"""
')do "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "https://google.com/search?q=%%~i"
- 移植参考代码以供使用电源外壳
@echo off
>nul chcp 65001 & color
for /f delims^= %%i in ('
powershell -nOp -c """$([uri]::EscapeDataString('Trois-Rivières, QC'))"""
')do <con: echo\%%~i && set "_string=%%~i" && echo\%%~i>.\My_Output_File.log
- 输出:
Trois-Rivi%C3%A8res%2C%20QC
- 在线解码:
- PowerShell一行程序:
$str="https://google.com/search?q=" + [uri]::EscapeDataString("Mèxico"); Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" $str