(已解决)如何处理 Program Files (x86) 作为用户输入?

(已解决)如何处理 Program Files (x86) 作为用户输入?

我编写了这个小备份脚本,它接受用户输入文件的源/目标。它可以很好地处理空格和,C:\Program Files\但似乎无法处理C:\Program Files (x86)\。这是我用来测试和解决问题的代码片段。

@echo off
set sourcedef=%USERPROFILE%\Desktop\Source

set /P sourceinp= Location of the source [Default=%sourcedef%] : 
if "%sourceinp%" == "" ( set source=%sourcedef% ) 
if not "%sourceinp%" == "" ( set source=%sourceinp% )
echo  Source folder set as : %source% 
pause

如果我尝试为其提供任何Program Files (x86)目录,cmd.exe 就会关闭商店。有什么建议吗?

编辑: 感谢用户“不是我“,非常感谢!

代码现在的样子:

@echo off

set source=%USERPROFILE%\Desktop\Source
set /p "source= Location of the source [Default=%source%] : " string ( str ^)  
echo Source folder set as : %source%
pause

答案1

@echo off 

set "_source_default=%USERPROFILE%\Desktop\Source"

^< nul <con: set /p "_source_input= Location of the source [Default=%_source_default%] : " 

if "%_source_input%" == "" (set "_source=%_source_default%") else set "_source=%_source_input%"
   
echo\Source folder set as %_source%
%__APPDIR__%Timeout.exe /t -1 & goto=:EOF

  • 您可以^< nul在行首使用 , 这是最近发现的逃避机械技巧,报告者为@杰布dostips.com,这将适用于用户输入之前的转义,并扩展到用户输入:

在此处输入图片描述


  • 将这一发现应用/调整到您的代码/输入将是:
^< nul <con: can literal escaping your line and your input 
    
^< nul <con: set /p "_source_input= Location of the source [Default=%_source_default%] : " 

关于输入这个/这些字符(和/或)以及他们的逃跑(如有必要)

rem :: Using only (
set /p "_input= Location : " string (  
rem ::     works ⁄⁄ output = string (  ⁄⁄  there's no need to escape

rem :: Using only )
set /p "_input= Location : " string )
rem ::     works ⁄⁄ output = string )  ⁄⁄  there's no need to escape

rem :: Using both ( and )
set /p "_input= Location : " string ( str ^)  
rem ::     works ⁄⁄ output = string ( str )  ⁄⁄  there's no need in (, only in ^)
  • 测试和输出:
F:\2020-SU\1572099>input_testv2.cmd
Location of the source [Default=C:\Users\ecker\Desktop\Source] : string (((((((
Source folder set as :  string (((((((

F:\2020-SU\1572099>input_testv2.cmd
Location of the source [Default=C:\Users\ecker\Desktop\Source] : ))))))))))) string
Source folder set as :  ))))))))))) string

F:\2020-SU\1572099>input_testv2.cmd
Location of the source [Default=C:\Users\ecker\Desktop\Source] : ( ( ( string ^) ^) ^)
Source folder set as :  ( ( ( string ) ) )

  • 注意:对于每个), 如果你有(先前的,形成的,那么是的,你需要使用每一对^), 额外的赔率 )))没有必要逃避:
F:\2020-SU\1572099>input_testv2.cmd
Location of the source [Default=C:\Users\ecker\Desktop\Source] : ( ( ( string ^) ^) ^) ))))
Source folder set as :  ( ( ( string ) ) ) ))))

答案2

如果我输入目录Program Files (x86)cmd会出现错误

这是因为()在脚本中是特殊字符cmd,需要使用进行转义^

无需转义:

F:\test>test
Location of the source [Default=C:\Users\David\Desktop\Source] : C:\Program Files (x86)
) was unexpected at this time.

F:\test>

使用转义符:

F:\test>test
Location of the source [Default=C:\Users\David\Desktop\Source] : C:\Program Files ^(x86^)
 Source folder set as : C:\Program Files (x86)
Press any key to continue . . .

进一步阅读

相关内容