【问题标题】:How to Call CMD.EXE from PowerShell with a Space in the Specified Command's Directory Name如何使用指定命令的目录名称中的空格从 PowerShell 调用 CMD.EXE
【发布时间】:2011-09-22 05:09:00
【问题描述】:

我有以下 PowerShell 脚本来验证我的 SVN 存储库:

$SVNAdminDir = 'C:\Program Files (x86)\VisualSVN Server\bin';
$RepositoryDir = 'C:\My Repositories\App1';
$_cmd = "`"$SVNAdminDir`\svnadmin`" verify `"$RepositoryDir`"";
Write-Host $_cmd; # Copying this into the command prompt runs without an issue...
cmd.exe /c $_cmd; # It's when I try to execute the command from PS that I get the error.

但是当我尝试执行它时,我收到以下错误消息:

cmd.exe : 'C:\Program' is not recognized as an internal or external command,
At line:5 char:12
+     cmd.exe <<<<  /c $_cmd;
    + CategoryInfo          : NotSpecified: ('C:\Program' is...ternal command,:String) [],     RemoteException
    + FullyQualifiedErrorId : NativeCommandError

operable program or batch file.

由于我实际上是在单引号内使用双引号设置 $cmd = '"C:\Program Files (x86)\VisualSVN Server\bin\svnadmin" verify "C:\My Repositories\App1"';,因此我期望 C:\Program Files (x86)\... 中的空格被传递正确。

我怀疑我缺少的字符串有些微不足道...

【问题讨论】:

    标签: svn powershell cmd visualsvn-server


    【解决方案1】:

    您需要像这样拨打cmd.exe

    cmd.exe /c "`"$_cmd`""
    

    您发送到cmd.exe 的命令需要完全用它们自己的引号括起来,而不仅仅是这些命令中的带空格的路径。这与 Powershell 解析字符串的方式有关,它需要将文字引号传递给 cmd.exe,以便它自己正确解析双引号的内容。

    例如,如果您已经在 cmd.exe 会话中并设置如下变量:

    C:\>set _cmd="C:\Program Files (x86)\VisualSVN Server\bin\svnadmin" verify "C:\My Repositories\App1"
    

    然后只需在命令行中扩展该变量即可:

    C:\>%_cmd%
    

    但是,如果将其传递给新的cmd.exe 会话,则还需要额外的引号:

    C:\>cmd.exe /c "%_cmd%"
    

    【讨论】:

    • 我无法让它在 PowerShell 中工作。 cmd.exe 不断出错,抱怨 'C:\Program' is not recognized as an internal or external command...。我正在运行 PowerShell 5.1。有什么想法吗?
    • 所以powershell转义字符是反引号?
    猜你喜欢
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多