batch:转义变量中的“和”之类的特殊字符

时间:2017-07-17 18:25:59

标签: powershell batch-file escaping batch-processing

此脚本(除了搜索重复文件外)还会将文件重命名为不包含特殊字符(在单个文件夹中)。当文件名包含等字符时,我仍然遇到问题。我尝试在delayedexpansion内添加,但也没有成功。

@echo off
echo "%~1" | find /i "system volume information" >nul && exit /b
echo "%~1" | find /i "s-1-5-21-3" >nul && exit /b
echo "%~1" | find /i "recycle" >nul && exit /b
cd /d %1 2>nul
if /i not "%~1"=="%cd%" echo cannot access %~n1 && exit /b

for %%v in (*) do set "original=%%~nxv" & call :validate
for /f "delims=" %%v in ('dir /b /a-d') do set "compare=%cd%\%%v" & call :detection
exit /b

:validate
:: add handling of “ and ”
set "newtitle=%original:!=%"
set "newtitle=%newtitle:”=%"
set "newtitle=%newtitle:&=and%"
setlocal enabledelayedexpansion
set "newtitle=!newtitle:%%= percent!"
setlocal disabledelayedexpansion
if not "%original%"=="%newtitle%" ren "%original%" "%newtitle%" && echo validated %newtitle%
goto next

:detection
:: this extrapolates %string% from beginning of filename
call d:\other\scripts\lootname.cmd "%compare%" data
set count=0
for %%v in ("%string%*") do set /a "count+=1"
for %%v in ("%string%*") do if not "%count%"=="1" echo "%%v"
:next

1 个答案:

答案 0 :(得分:1)

这个PowerShell one liner应该使用印刷引号来重新查找文件(来自当前文件夹)并删除它们。

$Search = '“|”';gci -r -file |where Name -Match $Search|Ren -NewName {$_.Name -replace $Search} -Confirm

只需粘贴到PowerShell控制台并让它运行即可。 -Confirm参数可让您询问每次重命名

示例输出:

Confirm
Are you sure you want to perform this action?
Performing the operation "Rename File" on target 
"Item: A:\A file name cannot have characters like “ and ” 
 Destination: A:\A file name cannot have characters like  and ".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

通常我会像这样嵌入powershell代码:

powershell -NoP -Command "$Search = '“|”';gci -r -file |where Name -Match $Search|Ren -NewName {$_.Name -replace $Search}"

但请记住,powershell通常在内部使用像Windows一样的UTF16,因此这里适用代码页限制 我无法将其粘贴到基于chcp 850的控制台中 - 印刷报价与普通报价交换。