0

I have made a small bat file for creating pre-built folders with user inputted name. It works fine until a user inputs a variable with a space. For example - the user inputting "John" would create a folder with sub folders called John (exactly what we want), however if a user was to enter Smith, John, the folder created will be called Smith,. How can I allow the script to register the user inputted space?

My code -

@echo off

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

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

I understand this is probably an easy fix but I have a very limited knowledge of code.

Thanks

Joshua Patterson
  • 313
  • 1
  • 2
  • 14
  • 3
    use the variable with `%findest%` - and delete the Quote before, your variable already contains all quotes that it Needs. – Stephan Dec 15 '15 at 06:56
  • 2
    Let me recommend to use the syntax `set "VAR=Value"` for _all_ your `set` commands in general; this avoids trouble with special characters, but does _not_ include the quotes in the `Value`; so there is always _one_ place to take care of surrounding quotes -- the _expansion_ of `"%VAR%"`... – aschipfl Dec 15 '15 at 07:18

1 Answers1

1

The highly recommended suggestions by Stephan and aschipfl applied to your code:

@echo off

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

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

See for example answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? for an explanation why set "VAR=Value" on assignment and "%VAR%" on expansion/reference is highly recommended even if the string to assign to a variable contains 1 more quotes.

Here is also an improved version which allows the string to be entered with double quotes and with each / (Linux/Mac directory separator) replaced by \ (Windows directory separator) and which removes last backslash from destination path because of ROBOCOPY interprets a single backslash at end of a directory path as escape character for the double quote:

@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
Mofi
  • 38,783
  • 14
  • 62
  • 115