powershell目录带空格_如何从PowerShell调用CMD.EXE与指定的命令的目录名称中的空格...

本文介绍了在PowerShell中使用带有空格的目录调用CMD命令时遇到的问题及解决方案。当尝试执行包含空格路径的CMD命令时,出现了'不是内部或外部命令'的错误。解决方法是在调用cmd.exe时,将整个命令包括路径用双引号括起来,以确保CMD正确解析含有空格的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

解决方案

You need to call cmd.exe like this:

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

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.

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"

Then simply expanding that variable at the commandline would work:

C:\>%_cmd%

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值