【问题标题】:Embedding PowerShell in batch批量嵌入 PowerShell
【发布时间】:2015-09-26 12:57:23
【问题描述】:

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

当我尝试运行时

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

我收到以下错误:

something :术语“something”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。

在 line:1 char:10

&{$var = 某事}

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

但是如果我运行类似的东西

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

然后一切都很好:/

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

提前致谢!

【问题讨论】:

标签: windows powershell batch-file command


【解决方案1】:

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

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

...或转义嵌套引号:

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

另一个例子:

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

【讨论】:

    【解决方案2】:

    可能有点晚了,但我编写了纯 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
    

    【讨论】:

    • Variant2 似乎不适用于脚本的 powershell 部分中的花括号
    • 使用 tmp 文件而不是 STDOUT 对我有用 @powershell -command "$tmpDir = [System.IO.Path]::GetTempPath(); Get-Content '%0' | Select -Skip 1 | Out-File $tmpDir\script.ps1; powershell -noprofile -File $tmpDir\script.ps1; Remove-Item $tmpDir -Recurse" & goto :eof
    猜你喜欢
    • 2021-05-06
    • 2017-11-03
    • 2021-11-26
    • 2016-01-03
    • 2019-08-09
    • 2020-03-31
    • 1970-01-01
    • 2011-02-15
    • 2017-06-22
    相关资源
    最近更新 更多