如何创建一个在没有外部 ps1 文件的情况下执行 powershell 脚本的 bat 文件?

Jas*_*son 1 windows powershell batch-file

存在一个现有问题,即双击此处找到的文件时如何运行 ps1 文件。但是我想知道是否有一个不需要 2 个单独文件的解决方案。

Jas*_*son 6

一种方法是将 Powershell 脚本嵌入到 .bat 文件中,并结合回显和注释:

echo `
REM | Out-Null <#
powershell.exe -ExecutionPolicy Bypass -Command "iex ((Get-Content \"%~f0\") -join \"`n\") | Out-Null"
goto :eof
#>

(powershell script here)

<#
:eof
::#>
Run Code Online (Sandbox Code Playgroud)

这会导致控制台输出中出现一些工件,但脚本成功嵌入到 bat 文件中运行。这可以正常工作,因为“echo”既是 Windows 命令行命令,也是 Powershell 命令。

编辑:几年后我在这里有了一个改进的版本:

@powershell.exe -ExecutionPolicy Bypass -Command "$_=((Get-Content \"%~f0\") -join \"`n\");iex $_.Substring($_.IndexOf(\"goto :\"+\"EOF\")+9)"
@goto :EOF

(powershell script here)
Run Code Online (Sandbox Code Playgroud)

改进:

  • 仅需要 2 行文件头(我不知道:EOF
  • 除非您从脚本执行此操作,否则没有控制台输出
  • 兼容,Write-Output因为仅将实际脚本内容传递给 powershell.exe