批量嵌入PowerShell

Embedding PowerShell in batch

我想通过批处理文件运行 一些 PowerShell 命令。非常相似 question 已被问到,但我不想 运行 来自批处理的单独 shell 文件。相反,我想将 嵌入 PowerShell 命令到批处理文件中。

当我尝试 运行

powershell -command "&{$var = "something"}"

我收到以下错误:

something : The term 'something' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

At line:1 char:10

&{$var = something}

CategoryInfo : ObjectNotFound: (something:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException

但是如果我运行像

powershell -command "&{echo "something"}" 

那么一切都很好:/

我是在犯语法错误还是什么?并且请不要给出诸如“使用批处理命令而不是使用 PowerShell 命令等...”之类的答案。

提前致谢!

将变量值定义为字符串时,不能使用嵌套引号。您可以使用撇号代替嵌套引号:

powershell -command "&{$var = 'something'; echo $var}"

... 或转义嵌套引号:

powershell -command "&{$var = \"something\"; echo $var}"

另一个例子:

powershell -command "&{$var = 'one'+\" two\"; echo $var}"

可能有点晚了,但我编写了纯 powershell 脚本并将完整的脚本嵌入到 .cmd 文件中以绕过执行策略设置。我有 2 种变体,选择您喜欢的一种。两者都是放在 .cmd 文件第一行的单行代码。从第二行开始,您只需在纯 powershell 中编程。无需修改 powershell 脚本中的任何内容。

变体 1:

@type "%0" | findstr /v "^@type \"%0\" | findstr /v " | PowerShell.exe -noprofile - & goto :eof

变量 2:

@powershell -command "(Get-Content '%0') | select -skip 1 " | powershell -noprofile - & goto :eof