批处理文件创建计划任务XML时如何正确转义双引号?
批处理拼接计划任务XML的双引号转义解决方案
问题根源
原代码中set parameter语句的连续双引号被批处理错误解析,导致语法报错" was unexpected at this time.,需要正确处理嵌套/连续双引号的转义,同时保证最终输出到XML的参数格式符合schtasks要求。
正确写法一(推荐:使用延迟扩展)
延迟扩展可以避免批处理在解析变量时处理内部引号,完美保留所需格式:
@echo off setlocal enabledelayedexpansion set "value1=eventvariable1" set "value2=eventvariable2" set "command=%windir%\system32\cmd.exe" :: 用!value1!/!value2!读取变量,避免解析引号冲突 set "parameter=/C""c:\basepath\FUNCTIONS\script.cmd" "net_up" "$(!value1!)" "$(!value2!)""" :: 输出到XML,尖括号用^转义,参数用!parameter!读取确保格式正确 echo ^<Command^>%command%^</Command^> >> file.xml echo ^<Arguments^>!parameter!^</Arguments^> >> file.xml endlocal
正确写法二(不用延迟扩展:手动转义引号)
通过^转义关键位置的双引号,让批处理正确识别变量边界:
@echo off set "value1=eventvariable1" set "value2=eventvariable2" set "command=%windir%\system32\cmd.exe" :: 转义/C后的第一个双引号,结尾补充转义的引号闭合变量 set "parameter=/C^""c:\basepath\FUNCTIONS\script.cmd" "net_up" "$(%value1%)" "$(%value2%)"""" echo ^<Command^>%command%^</Command^> >> file.xml echo ^<Arguments^>%parameter%^</Arguments^> >> file.xml
效果验证
两种写法最终输出到file.xml的<Arguments>内容均为:
<Arguments>/C""c:\basepath\FUNCTIONS\script.cmd" "net_up" "$(eventvariable1)" "$(eventvariable2)""</Arguments>
完全匹配schtasks GUI中有效的参数格式,可正常导入创建计划任务。
内容的提问来源于stack exchange,提问作者user2956477
相关产品推荐
相关产品推荐

