在 PowerShell 中执行的命令(变量用引号引起来)会失败。为什么?
我在使用 PoSH 将带引号的变量嵌入到外部命令时遇到了令人惊讶的困难。例如,此命令
dfsradmin membership list /rgname:`"stuff I want`"
给出以下预期结果:
Failed:
Replication group with name stuff I want cannot be found.
但是此命令
$group = "stuff I want"
dfsradmin membership list /rgname:`"$group`"
失败并出现此错误:
Failed:
The subobject "/rgname:"stuff is not a valid subobject.
这是 Powershell 的错误还是我遗漏/误解了某些内容?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是的,Powershell(包括 v2.0)中存在与此相关的已知问题: http://connect.microsoft.com/PowerShell/feedback/details/376207/executing-commands-which-require-quotes-and-variables-is-practically-impossible
查看是否上面链接中讨论的替代方案适合您。我无法尝试,因为我没有该可执行文件。
另外,
echoargs.exe
是一个有用的工具,您可以使用它来查看从 Powershell 接收到的参数。Yeah there are known issues in Powershell ( including v2.0) around this: http://connect.microsoft.com/PowerShell/feedback/details/376207/executing-commands-which-require-quotes-and-variables-is-practically-impossible
See if the alternatives discussed in the link above work for you. I cannot try it out as I don't have that executable.
Also
echoargs.exe
is a useful tool that you can use to see what arguments have been recevied from Powershell.我发现定义
然后使用
/command$quote"test"$quote
也有效I found that defining
and then using
/command$quote"test"$quote
works as well无需在引号前面添加反勾号。这对你有用吗?
There's no need to add back ticks in front of quotes. Does this work for you?
因此,我能够通过在 CMD.exe 中执行它并进行字符串操作来获得我需要的内容来解决这个问题。
感谢您的帮助!我希望这个问题已在 Powershell 3.0 中得到解决。
So I was able to get around this by executing it in CMD.exe and doing string manipulations to get what I need.
Thanks for the help! I hope this has been resolved in Powershell 3.0.
我找到了一种解决方法,它不调用 cmd,而是使用 Invoke-Expression。该命令必须首先放入变量中:
$var = "string with space"
$command = "first part " + [char]96 + [char]34 + $var + [char]96 + [char]34 + “第二部分”
Invoke-Expression $command
不太漂亮,但它有效。如果您愿意,可以将 [char]96 替换为 '`',将 [char]34 替换为 '"'。如果您经常使用它,则很容易创建一个可以执行此操作的函数。
I found a workaround which doesn't call cmd but uses Invoke-Expression instead. The command has to be put in a variable first:
$var = "string with spaces"
$command = "first part " + [char]96 + [char]34 + $var + [char]96 + [char]34 + " second part"
Invoke-Expression $command
Not that pretty but it works. You can replace [char]96 with '`' and [char]34 with '"' if you prefer. Easy to create a function which does it if you use it a lot.
以上所有内容对我来说都不起作用,但基于卡洛斯的想法,这是发布的解决方案 此处
All of the above did not work for me but based on Carlos idea, this is the solution that worked posted here
我知道这是旧线程,但只是在这里发布,以防我的解决方案适用于某人,就像它适用于我一样。
这个特定的命令(dfsradmin)需要本机看到的引号,因此我只是将值用单引号中的引号括起来,从而也传递引号:
或者如果使用通过变量:
I know this is old thread but just posting here in case my solution works for somebody as it worked for me.
This particular command (dfsradmin) expects natively seen quotes so I just enclosed value with quotes in single quotes thus passing quotes as well:
or if using through variable: