首页 > 解决方案 > 将变量传递给启动 powershell 命令

问题描述

我想将字符串变量传递给在新的 powershell 窗口中运行的命令。

$word = "bird"
start PowerShell { echo $word; pause }

我该怎么做呢?

标签: powershell

解决方案


不知何故,它在没有大括号的情况下效果更好,并使用双引号来解释变量。我猜脚本块被启动进程转换为字符串。“Powershell -Command”是隐含的。

start powershell "echo $word; pause"

或者这适用于呼叫操作员:

start PowerShell "& { echo $word; pause }"

“电源外壳 -?” 有点涉及到这一点。

-Command

...
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe 
in Windows PowerShell. 

...
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.

To write a string that runs a Windows PowerShell command, use the format:
    "& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.

推荐阅读