Getting A Constant Value From A .NET Executable in PowerShell
[PowerShell, .NET]
PowerShell is an excellent, cross-platform scripting solution that you can use to automate various tasks in Windows, Linux, and Unix environments. The fact that it has full access to the entire .NET ecosystem is the icing on the cake.
I use it for a bunch of quick scripts and utilities across the various devices I work on.
Recently, I needed to load the value of a constant that was in a .NET application, so that I could use it for registration of the application.
The steps are as follows:
- Obtain the path to the actual application
- Load the assembly
- Extract the constant value
Given that the application was in the same path as the application executable, I made use of the knowledge from the last post, “Getting The Current Path Of An Executing PowerShell Script”, and then used the Join-Path cmdlet to build the path.
$path = (Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) 'MyKillerApp.exe')
Write-Host $path
Next, we load the assembly.
In .NET (not .NET Framework), when you compile an executable, among the artifacts that are generated is what we think of as the application executable, in this case MyKillerApp
.
This, however, is just a bootstrapper. Your code actually gets compiled into a DLL
with the same name.
It is in this DLL that we can find our constant.
We then use native PowerShell cmdLet
, Add-Type, to load the type, passing it the path.
# Load the type
Add-Type -Path $path
Finally, we extract the constant.
# Fetch the constant value
$ApplicationName = ([MyKillerApp.AppInfo]::ApplicationName)
The complete script is as follows:
# Get the path to the exe
$path = (Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) 'MyKillerApp.dll')
# Print path
Write-Host $path
# Load the type
Add-Type -Path $path
# Fetch the constant value
$ApplicationName = ([MyKillerApp.AppInfo]::ApplicationName)
# Print the value
Write-Host $ApplicationName
If we run the script, we should see the following:
./Script.ps1
/Users/rad/Projects/BlogCode/PowerShellConstant/MyKillerApp/bin/Debug/net9.0/MyKillerApp.dll
My Killer Application
Remember that you must run the script from a PowerShell shell.
You can launch that as follows:
pwsh
If you don’t have PowerShell installed, here are the installation instructions.
TLDR
PowerShell can extract constants and other values from .NET assemblies.
The code is in my GitHub.
Happy hacking!