【问题标题】:Strange parameter substitution in CMD (BAT) fileCMD(BAT)文件中的奇怪参数替换
【发布时间】:2014-04-19 23:52:17
【问题描述】:

我编写了一个 powershell 脚本,希望能够在 Windows 上从批处理脚本运行。

powershell脚本位于blizzard-main.ps1

CMD 脚本如下所示:

@ECHO OFF
powershell -command "& { . %~dp0%\blizzard-main.ps1; Blizzard-Main %1}"
:EOF

运行时遇到的奇怪错误是:

. : The term 'C:\Users\mzr\Documents\GitHub\ProductionTools\Blizzard\Dist\Blizzard\bin\1'
is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is
correct and try again.

At line:1 char:7

+ & { . C:\Users\mzr\Documents\GitHub\ProductionTools\Blizzard\Dist\Blizzard\bin\1 ...
[SNIP]

如果我像这样使用 echo 调试脚本:

@ECHO OFF
ECHO powershell -command "& { . %~dp0%\blizzard-main.ps1; Blizzard-Main %1}"
:EOF

我得到了这个有趣的输出:

powershell -command "& { . C:\Users\mzr\Documents\GitHub\ProductionTools\Blizzard\Dist\Blizzard\bin\1}"

很明显有些事情搞砸了。如果我删除%1,脚本会被执行,但是第一个参数没有按照它应该的方式传递。

【问题讨论】:

    标签: windows batch-file powershell cmd


    【解决方案1】:

    我自己发现了错误:

    @ECHO OFF
    ECHO powershell -command "& { . %~dp0%\blizzard-main.ps1; Blizzard-Main %1}"
    :EOF
    

    应该改为

    @ECHO OFF
    ECHO powershell -command "& { . %~dp0\blizzard-main.ps1; Blizzard-Main %1}"
    :EOF
    

    (我有一个额外的%。)

    【讨论】:

      【解决方案2】:

      请记住,%~dp0 包含一个斜杠,因此您可能不想再在其上添加另一个斜杠。另外,我建议始终在文件路径两边加上双引号,以防路径中有空格。

      把你的命令行改成这样:

      powershell -command "& { . \"%~dp0%blizzard-main.ps1\"; Blizzard-Main %1}"
      

      【讨论】:

        猜你喜欢
        • 2012-12-18
        • 1970-01-01
        • 1970-01-01
        • 2011-09-25
        • 2012-12-27
        • 2011-04-12
        • 2021-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多