我尝试通过设置变量并打印它来运行简单的PowerShell命令。
这就是我想要做的事情:
powershell -command "& {$name=\"hi\"; echo $name}"
但它失败了:
The string is missing the terminator: ".
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
调用操作符(&
)可以与命令一起使用,例如:
powershell -command "& {&echo hi}"
我读到了调用操作符以及如何使用-command
选项执行命令并使用-File
选项等执行脚本。它们按预期工作。但我尝试设置变量并按上述方式打印它也是行不通的。我怀疑-command
仅适用于命令。知道如何实现我上面的工作吗?
答案 0 :(得分:2)
从DOS shell开始工作:
powershell -command "& {$name='hi'; echo $name}"
但你的代码也有效。
从Powershell控制台使用:
powershell -command {$name='hi'; echo $name}