将多个 PowerShell 脚本转换成一个 Exe 文件

Convert multiple PowerShell scripts into an Exe file

我的 powershell 脚本很少。 我可以将 powershell 脚本转换成一个 exe 文件吗?我需要按顺序将它设置为 运行。例如,使用第一个脚本安装后,需要安装第二个脚本,然后是 3、4、5 个脚本。

在最简单的情况下,您可以使用以下方法将您的脚本合并为一个脚本,然后您可以将其打包为可执行文件:

$scripts = 'script1.ps1', 'script2.ps1', 'script3.ps1'
(Get-Item $scripts | ForEach-Object { 
  "& {{`n{0}`n}}" -f (Get-Content -Raw $_.FullName) 
}) -join "`n`n" > 'combined.ps1'

请注意,这是一种简单但可扩展的方法:如所写,不支持参数,也没有错误处理:原始脚本的相应内容只是按顺序执行 (&) , 作为脚本块 ({ ... }).

您可以将组合脚本 combined.ps1 编译为可执行文件 ,例如 combined.exe,如下所示,使用 PS2EXE-GUI 项目的ps2exe.ps1 脚本(流行的原创但已过时的 PS2EXE 项目的更新且功能更全面的版本)。

# Create a PSv2-compatible executable.
# Omit -runtime20 to create an executable for the same PowerShell version
# that runs the script.
ps2exe -inputFile combined.ps1 -outputFile combined.exe -runtime20

警告:通常,运行 生成的可执行文件要求执行机器安装 PowerShell,但 由于目标 -runtime20 - 为了与 v2 兼容 - 还必须安装 .NET Framework 2.0 CLR(请注意,它还附带 .NET Framework 3.5),这在最近版本的 Windows.

中不再默认为真