简体   繁体   English

在命令行上执行一个简单的powershell命令

[英]Executing a simple powershell command on the command line

I try to run a simple powershell command by setting a variable and printing it. 我尝试通过设置变量并打印来运行简单的powershell命令。

This is what I want to do: 这就是我想做的:

powershell -command "& {$name=\"hi\"; echo $name}"

But it fails with: 但是它失败了:

The string is missing the terminator: ".
   + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
   + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

The invoke operator ( & ) works fine with commands such as: invoke操作符( & )可以很好地与以下命令配合使用:

 powershell -command "& {&echo hi}"

I read about the invoking operator and how to execute commands with -command option and executing scripts with -File option etc. They are working as expected. 我看了一下调用操作,以及如何执行与命令-command和执行脚本使用选项-File选项等,它们是可以预期工作。 But my attempts to do the same for setting a variable and printing it as above doesn't work. 但是我尝试执行相同的操作来设置变量并如上所述打印它不起作用。 I suspect -command works with only commands . 我怀疑-command仅适用于command Any idea how to achieve what I do above? 任何想法如何实现我在上面的工作?

from a DOS shell this works: 从DOS外壳中可以正常工作:

powershell -command "& {$name='hi'; echo $name}"

but also your code works. 而且您的代码也可以。

From a Powershell console use this: 在Powershell控制台中使用以下命令:

powershell -command {$name='hi'; echo $name}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM