更新时间:2023-01-08 19:15:31
在最简单的情况下,您可以使用以下方法将脚本合并为一个脚本,然后将其打包为一个可执行文件:
In the simplest case, you can use the following approach to merge your scripts into a single script that you can then package as an executable:
$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'
请注意,这是一种简单但可扩展的方法:按照书面规定,不支持参数,也没有错误处理:原始脚本的各个内容作为脚本块按顺序简单地按顺序执行(&
) ({ ... }
).
Note that this is a simplistic, but extensible approach: As written, there is no support for parameters, and no error handling: the respective contents of the original scripts are simply executed (&
) in sequence, as script blocks ({ ... }
).
您可以使用 PS2EXE 项目).
You can compile the combined script, combined.ps1
to an executable, say, combined.exe
, as follows, using the PS2EXE-GUI project's ps2exe.ps1
script (an updated and more fully featured version of the popular original, but obsolescent PS2EXE project).
# 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的最新版本中不再适用
Caveat: Generally, running the resulting executable requires the executing machine to have PowerShell installed, but due to targeting -runtime20
- in an effort to be v2-compatible - the .NET Framework 2.0 CLR must also be installed (note that it also comes with .NET Framework 3.5), which is no longer true by default in recent versions of Windows.