我怎样才能在用户输入的 bat 脚本变量中有一个 space

How can I have a space in user inputted variable for bat script

我制作了一个小的 bat 文件,用于使用用户输入的名称创建预建文件夹。它工作正常,直到用户输入带有 space 的变量。例如 - 用户输入 "John" 将创建一个文件夹,其中包含名为 John 的子文件夹(正是我们想要的),但是如果用户输入 Smith, John,则创建的文件夹将称为 Smith,。如何让脚本注册用户输入的 space?

我的代码-

@echo off

set /P dest=Enter Name: 
set findest="Z:\ProjectIT\copy\%dest%"

robocopy Z:\ProjectIT\copy\xcopy "%findest

我知道这可能是一个简单的解决方法,但我对代码的了解非常有限。

谢谢

Stephan and aschipfl 强烈推荐的建议应用于您的代码:

@echo off

set /P "dest=Enter name: "
set "findest=Z:\ProjectIT\copy\%dest%"

%SystemRoot%\System32\robocopy.exe Z:\ProjectIT\copy\xcopy "%findest%"

请参阅 Why is no string output with 'echo %var%' after using 'set var = text' on command line? 上的示例答案,以了解为什么强烈建议在赋值时使用 set "VAR=Value" 并在 expansion/reference 上使用 "%VAR%",即使要分配给变量的字符串也是如此包含 1 个引号。

这里还有一个改进的版本,它允许用双引号输入字符串,并且每个 /(Linux/Mac 目录分隔符)替换为 \(Windows 目录分隔符)并从目标路径中删除最后一个反斜杠,因为 ROBOCOPY 将目录路径末尾的单个反斜杠解释为双引号的转义字符:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

:EnterName
set "dest=""
set /P "dest=Enter name: "
set "dest=%dest:"=%"
if not defined dest cls & goto EnterName
set "dest=%dest:/=\%"
if "%dest:~-1%" == "\" set "dest=%dest:~0,-1%"
if not defined dest cls & goto EnterName

set "findest=Z:\ProjectIT\copy\%dest%"

%SystemRoot%\System32\robocopy.exe Z:\ProjectIT\copy\xcopy "%findest%"
endlocal