简体   繁体   中英

How do I pass a directory path with spaces into a .cmd script?

I am trying to pass two arguments into my .cmd script to create a folder for arg1 and define a source dir for arg2. The source dir is "Shared Documents". The problem is that I cannot pass a space or a wildcard into the argument without it stating that the path does not exist. I have also tried passing it with quotes, same results.

@set dirYr=%1
@set dir1=%2

@set connectionroot=https://somewhere.com/sites/foo_bar/foobar/FooBar::Source path
@set sourcepath=https://somewhere.com/sites/foo_bar/foobar/FooBar\%dir1%::Destination path
@set destinationpath=\\foo\bar\%dirYr%\%dir1%

::Check commandline argument to make sure that %2 is present.
IF NOT DEFINED dir1 (echo USAGE: foo_bar.cmd ^<YYYY^>^<Directory^|Filename^>GOTO badexit)

Any direction on how to get the script to accept an argument with spaces would be appreciated. I know that the argument needs quotes, I just do not know the syntax to have the quotes removed before it interpolates into the variable

Assuming you are executing your batch file like this:

myscript.bat "arg 1" "arg 2"

The best practice for using those command line arguments and defining variables would look something like this.

@echo off
set "dirYr=%~1"
set "dir1=%~2"

set "connectionroot=https://somewhere.com/sites/foo_bar/foobar/FooBar"
set "sourcepath=https://somewhere.com/sites/foo_bar/foobar/FooBar\%dir1%"
set "destinationpath=\\foo\bar\%dirYr%\%dir1%"

::Check commandline argument to make sure that %2 is present.
IF NOT DEFINED dir1 (echo USAGE: foo_bar.cmd ^<YYYY^>^<Directory^|Filename^>GOTO badexit)

Now remember if you are using those variables with spaces you will need to quote the variables when using them as well. Best practice is to always use quotes regardless of needing them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM