批量删除双引号或正确转义&符号

时间:2014-12-12 20:46:30

标签: batch-file

我想执行一些传递参数的程序。参数根据星期几而变化,它是一个网址

代码:

@echo off
setlocal enableDelayedExpansion
for /f %%a in ('wmic path win32_localtime get dayofweek /format:list ^| findstr "="') do (set %%a)

if %dayofweek% == 7(
    EXIT
)
set link="http://backlog.telecom.pt/maps/selector/download?map_name=workline_fornecedores&organization_id=1"

if %dayofweek%==5 (
    set link="http://backlog.telecom.pt/maps/selector/download?map_name=all_fornecedores&organization_id=1"
)

REM start /wait D:\Planview\Services\BackLog_Integration_Client_Service\Backlog_Integration_Client_Exe\Backlog_Integration_Client_Exe.exe %link%
REM timeout /t 600 /nobreak > NUL
REM start D:\Planview\Services\PV_Backlog_ProcessData_Service\PV_Backlof_ProcessData_Exe\PV_Backlog_ProcessData_Exe.exe

我读过^之前&会努力逃避& char,但对我来说它从来没有做过,我设法做到的唯一方法是enableDelayedExpansion并将URL封装在“,但这给我带来了一个问题..我的变量而不是url有”url“。

我尝试set link=%link:"%但是没有用。

1 个答案:

答案 0 :(得分:2)

我会尝试通过简单的例子给你一些建议:

@setlocal enableDelayedExpansion

rem This fails because & is a "poison" character (an instruction or operator)
echo abc&xyz

rem This succeeds because & is escaped
echo abc^&xyz

rem This succeeds because & is quoted
echo "abc&xyz"

rem This succeeds, but it consumes the escape: stored value = abc&xyz
set test=abc^&xyz

rem So this fails because & is not escaped
echo %test%

rem You could "fix" above by double escaping when doing SET so stored value = abc^&xyz
rem But I don't like this - I pretty much never do it
set test=abc^^^&xyz

rem Now this works
echo %test% 

rem Better to single escape and use delayed expansion.
set test=abc^&xyz
rem This works because poison characters don't bother delayed expansion
echo !test!

rem You could use quotes instead of escape, but now quotes are in value
set test="abc&xyz"
rem Delayed expansion is not needed because value is quoted
echo %test%

rem Putting the leading quote before the variable still quotes everything
rem But now the quotes are not in the value, as desired. Value = abc&xyz
set "test=abc&xyz"
rem Now you must use delayed expansion because value is not quoted
echo !test!

因此,当涉及毒物字符时我喜欢使用的一般经验法则:

  • 在设置变量时使用整个作业的引号:set "var=value"
  • 展开变量时使用延迟展开:!var!

如果这些规则解决了所有问题,那会不会很好。但当然批量并不那么简单。在某些情况下,这些简单的规则会失败,但它应该足以让你开始。