【问题标题】:How do I pass a directory path with spaces into a .cmd script?如何将带有空格的目录路径传递给 .cmd 脚本?
【发布时间】:2019-06-30 23:28:45
【问题描述】:

我正在尝试将两个参数传递到我的 .cmd 脚本中,以便为 arg1 创建一个文件夹并为 arg2 定义一个源目录。源目录是“共享文档”。问题是我不能将空格或通配符传递到参数中,而不说明路径不存在。我也试过用引号传递它,结果相同。

@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)

任何关于如何让脚本接受带空格的参数的指导将不胜感激。我知道参数需要引号,我只是不知道在插入变量之前删除引号的语法

【问题讨论】:

  • 您没有展示如何执行带引号和不带引号的脚本的示例。不管你需要使用引号。
  • 另外,你的问题中没有一行代码会给你一个路径不存在的错误。

标签: batch-file path spaces util.cmd


【解决方案1】:

假设您正在像这样执行批处理文件:

myscript.bat "arg 1" "arg 2"

使用这些命令行参数和定义变量的最佳做法如下所示。

@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)

现在请记住,如果您使用带空格的变量,则在使用它们时也需要引用变量。最佳做法是始终使用引号,无论是否需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    相关资源
    最近更新 更多