
Модуль для компиляции скриптов PowerShell в исполняемые файлы
Доработка отличного скрипта Инго Карштайна с поддержкой GUI. Вывод и ввод через GUI активируются одним переключателем, создаются настоящие исполняемые файлы Windows. Компилирует только скрипты, совместимые с Powershell 5.x. С опциональным графическим интерфейсом Win-PS2EXE.
Версия модуля.
Версию на основе скрипта можно найти здесь (https://github.com/MScholtes/TechNet-Gallery).
Автор: Markus Scholtes
Версия: 1.0.18
Дата: 2026-06-06
PS C:\> Install-Module ps2exe
или скачайте отсюда: https://www.powershellgallery.com/packages/ps2exe/.
Invoke-ps2exe .\source.ps1 .\target.exe
или
ps2exe .\source.ps1 .\target.exe
компилирует «source.ps1» в исполняемый файл target.exe (если «.\target.exe» опущен, вывод записывается в «.\source.exe»).
или запустите Win-PS2EXE для графического интерфейса с помощью
Win-PS2EXE
ps2exe [-inputFile] '<file_name>' [[-outputFile] '<file_name>']
[-prepareDebug] [-x86|-x64] [-lcid <id>] [-STA|-MTA] [-noConsole] [-conHost] [-UNICODEEncoding]
[-credentialGUI] [-iconFile '<filename>'] [-$embedFiles <hashtable>] [-title '<title>'] [-description '<description>']
[-company '<company>'] [-product '<product>'] [-copyright '<copyright>'] [-trademark '<trademark>']
[-version '<version>'] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-exitOnCancel]
[-DPIAware] [-requireAdmin] [-supportOS] [-virtualize] [-longPaths]
inputFile = Powershell script that you want to convert to executable (file has to be UTF8 or UTF16 encoded)
outputFile = destination executable file name or folder, defaults to inputFile with extension '.exe'
prepareDebug = create helpful information for debugging
x86 or x64 = compile for 32-bit or 64-bit runtime only
lcid = location ID for the compiled executable. Current user culture if not specified
STA or MTA = 'Single Thread Apartment' or 'Multi Thread Apartment' mode
noConsole = the resulting executable will be a Windows Forms app without a console window
conHost = force start with conhost as console instead of Windows Terminal (disables redirections)
UNICODEEncoding = encode output as UNICODE in console mode
credentialGUI = use GUI for prompting credentials in console mode
iconFile = icon file name for the compiled executable
embedFiles = files to embed given as hash, will be extracted to key of hash, source file names must be unique
(e.g. -embedFiles @{'Targetfilepath'='Sourcefilepath'} )
title = title information (displayed in details tab of Windows Explorer's properties dialog)
description = description information (not displayed, but embedded in executable)
company = company information (not displayed, but embedded in executable)
product = product information (displayed in details tab of Windows Explorer's properties dialog)
copyright = copyright information (displayed in details tab of Windows Explorer's properties dialog)
trademark = trademark information (displayed in details tab of Windows Explorer's properties dialog)
version = version information (displayed in details tab of Windows Explorer's properties dialog)
configFile = write config file (<outputfile>.exe.config)
noOutput = the resulting executable will generate no standard output (includes verbose and information channel)
noError = the resulting executable will generate no error output (includes warning and debug channel)
noVisualStyles = disable visual styles for a generated windows GUI application (only with -noConsole)
exitOnCancel = exits program when Cancel or "X" is selected in a Read-Host input box (only with -noConsole)
DPIAware = if display scaling is activated, GUI controls will be scaled if possible (only with -noConsole)
requireAdmin = if UAC is enabled, compiled executable run only in elevated context (UAC dialog appears if required)
supportOS = use functions of newest Windows versions (execute [Environment]::OSVersion to see the difference)
virtualize = application virtualization is activated (forcing x86 runtime)
longPaths = enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10)
Сгенерированный исполняемый файл имеет следующие зарезервированные параметры:
-? [<MODIFIER>] Powershell help text of the script inside the executable. The optional parameter combination
"-? -detailed", "-? -examples" or "-? -full" can be used to get the appropriate help text.
-debug Forces the executable to be debugged. It calls "System.Diagnostics.Debugger.Launch()".
-extract:<FILENAME> Extracts the powerShell script inside the executable and saves it as FILENAME.
The script will not be executed.
-wait At the end of the script execution it writes "Hit any key to exit..." and waits for a key to be pressed.
-end All following options will be passed to the script inside the executable.
All preceding options are used by the executable itself and will not be passed to the script.
PS2EXE можно использовать с Powershell Core. Для этого просто установите модуль PS2EXE в Powershell Core, как описано выше. Но поскольку .Net Core не поставляется с компилятором, используется компилятор .Net Framework (.Net Framework и Powershell 5.1 входят в состав Windows).
По этой причине PS2EXE может компилировать только скрипты, совместимые с Powershell 5.1, и создаёт двоичные файлы .Net 4.x, но при этом может использоваться напрямую в любой поддерживаемой ОС Windows без дополнительных зависимостей.
С помощью параметра -embedFiles и хеш-таблицы с путями к файлам эти файлы будут встроены в скомпилированный исполняемый файл. При запуске исполняемого файла эти файлы будут записаны на диск по указанным путям, например -embedFiles @{'Targetfilepath1'='Sourcefilepath1';'Targetfilepath2'='Sourcefilepath2'}. Имена исходных файлов должны быть уникальными. Допускаются абсолютные и относительные пути. Для целевых путей относительный путь, начинающийся с '.\', интерпретируется как относительный к исполняемому файлу, без ведущего '.\' — как относительный к текущему пути во время выполнения. Директории создаются автоматически при запуске, если необходимо. В целевом пути переменные окружения в нотации cmd.exe, такие как %TEMP% или %APPDATA%, разворачиваются во время выполнения. Сбой при создании одного из встроенных файлов немедленно остановит выполнение скомпилированного исполняемого файла.
Основные команды ввода/вывода пришлось переписать на C# для PS2EXE. Не реализованы: Write-Progress в консольном режиме (слишком много работы) и Start-Transcript/Stop-Transcript (нет подходящей эталонной реализации от Microsoft).
По умолчанию в powershell вывод командлетов форматируется построчно (как массив строк). Если ваша команда генерирует 10 строк вывода и вы используете вывод в GUI, появится 10 окон сообщений, каждое из которых ожидает нажатия OK. Чтобы этого избежать, передайте вывод вашей команды через командлет Out-String. Это преобразует вывод в один строковый массив из 10 строк, и весь вывод будет показан в одном окне сообщения (например: dir C:\ | Out-String).