如何从PowerShell调用CMD.EXE与指定的命令的目录名称中的空格 [英] How to Call CMD.EXE from PowerShell with a Space in the Specified Command's Directory Name

查看:607
本文介绍了如何从PowerShell调用CMD.EXE与指定的命令的目录名称中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following PowerShell script for verifying my SVN repositories:

$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.

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

But when I try to execute it, I'm receiving the following error message:

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:\程序文件(x86)\VisualSVN Server\bin \svnadmin验证C:\My Repositories\App1'; 与单引号内的双引号,我期待 C:\ Program Files(x86)\ ... 中的空格可以正确传递。

Since I'm essentially setting $cmd = '"C:\Program Files (x86)\VisualSVN Server\bin\svnadmin" verify "C:\My Repositories\App1"'; with the double quotes inside of the single quotes, I was expecting the space in C:\Program Files (x86)\... to be passed correctly.

我怀疑有一些小事我缺少的字符串...

I suspect there's something trivial with the string that I'm missing...

推荐答案

您需要调用 cmd.exe 这样:

You need to call cmd.exe like this:

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

发送到 cmd.exe 的命令需要完全包装在自己的引号中,不仅仅是那些命令的一部分的路径与空格。这与Powershell如何解析字符串有关,它需要传递字面引用到 cmd.exe ,以便它自己解析双引号的内容

The commands you send to cmd.exe need to be entirely wrapped in their own quotes, not just the paths-with-spaces that are part of those commands. This has to do with how Powershell parses the string and it needs to pass literal quotes to cmd.exe so that it in turn does its own parsing of the contents of double-quotes correctly.

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

For example, if you were already in a cmd.exe session and set a variable like this:

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

在命令行工作:

C:\>%_cmd%

但是,如果将它传递给新的 cmd.exe 会话, :

However, if passing it to a new cmd.exe session, it would also need extra quotes:

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

这篇关于如何从PowerShell调用CMD.EXE与指定的命令的目录名称中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆