如何从 PowerShell 调用 CMD.EXE,并在指定命令的目录名称中包含空格
我有以下 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)\... 正确传递。
我怀疑我丢失的字符串有一些微不足道的东西......
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.
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要像这样调用
cmd.exe
:发送到
cmd.exe
的命令需要完全用自己的引号括起来,而不仅仅是带空格的路径这是这些命令的一部分。这与 Powershell 解析字符串的方式有关,它需要将文字引号传递给 cmd.exe,以便它能够正确解析双引号的内容。例如,如果您已经在
cmd.exe
会话中并设置了如下变量:那么只需在命令行中扩展该变量即可:
但是,如果将其传递给新的
cmd .exe
会话,它还需要额外的引号:You need to call
cmd.exe
like this: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 tocmd.exe
so that it in turn does its own parsing of the contents of double-quotes correctly.For example, if you were already in a
cmd.exe
session and set a variable like this:Then simply expanding that variable at the commandline would work:
However, if passing it to a new
cmd.exe
session, it would also need extra quotes: