How to Convert PowerShell File to an Executable File
We can invoke PowerShell scripts (PS1
) in many different ways, but they all have one downfall, we cannot simply run them like a standard Windows executable program (EXE
). We want to prevent editing the code in a script or make it easier for our users to run scripts.
So it is time to learn how to convert a PS1
to an EXE
. This article will discuss using the PS1
to the EXE
module and properly converting PowerShell files to executable files.
Use PSEXE
Utility to Convert PS1
to EXE
in PowerShell
PS2EXE
is a free, open-source Windows PowerShell module that does not convert the PowerShell script to another language.
Instead, it encapsulates the PowerShell script with a lightweight PowerShell host written in the C# language and compiles the dynamically generated C# code in memory to an executable file.
Install the PSEXE
Module in PowerShell
Since PS2EXE
uses the module to convert our script to an executable, we need to install it from the PowerShell Gallery. Follow the instructions to install the PS2EXE
utility module.
-
Open a PowerShell console as an administrator.
-
Run the
Install-Module
cmdlet to download and install the module from the PowerShell Gallery.Install-Module ps2exe
-
Type
Y
and press Enter once we see the prompt about an untrusted repository. Don’t worry; this message is harmless.Untrusted repository You are importing the modules from an untrusted location. If you trust this location, change its InstallationPolicy by running the Set-PSRepository command. Are you certain you want to install the modules from the 'PSGallery'? [Y] Yes [N] No [?] Help (default is "N"): Y
Convert PS1
to EXE
Using PowerShell
Converting a single Windows PowerShell script to an executable file via the command line requires a single line using the main PS2EXE
command (Invoke-PS2EXE
). The command is then followed by the script’s path to convert and the path to the executable file that we would like to create.
## Use the cmdlet
Invoke-PS2EXE .\test.ps1 .\sample.exe
## Using the alias
ps2exe .\test.ps1 .\sample.exe
We can now run sample.exe
, which will invoke the code defined in the source.ps1
script. If we did not use the NoConsole
parameter while converting our script, a PowerShell console would appear when running the sample.exe
file.
Hide the Console
In the previous example, when running sample.exe
, a typical PowerShell console will appear. Most of the time, we don’t want to see this.
We can use the NoConsole
parameter when creating the EXE
to prevent that.
Invoke-ps2exe "D:\PS\Script.ps1" "D:\PS\Sample.exe" -noConsole
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn