Get the source code of the PowerShell cmdlets

Today during a workshop a student asked me about how to get the source code of PowerShell commands (cmdlets).

That was a good question, so I decided to share it here with you.

For those who don't know, PowerShell is built on top of the .NET Framework. So, it uses and extends the .NET Framework. That means that its commands (cmdlets) are compiled into managed DLLs (.NET Framework).

As result, PowerShell commands are not compiled direct to machine language, but to the intermediate language (IL) of the .NET Framework. More details at: https://msdn.microsoft.com/us-en/library/z1zx9t92.aspx.

Once we know that, it is easy to extract the source code of the DLLs of PowerShell cmdlets.

Example:

The Get-Date command returns the current date and time. To get its source, it is necessary to identify where is the DLL associated with the command. This is possible via the following command:

(Get-Command get-date).DLL

The second step is to identify which is the DLL that corresponds to the get-date cmdlet. For both:

(Get-Command get-date).ImplementingType

Through these commands it is possible to get the following results:

DLL:

C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Commands.Utility\v4.0_3.0.0.0__31bf3856ad364e35\Microsoft.PowerShell.Commands.Utility.dll

Method:

GetDateCommand

Once we have the DLL and that we know that it is managed (written in .NET and compiled in IL), it is easy to get the source code through reverse engineering. There are several tools for this purpose, I will use the ILSpy which is free.

Using ILSpy, you can query all the methods available in the DLL. The following figure displays .NET code part of the Get-Date cmdlet, in case the GetDateCommand: Get-Date

 

I hope you have enjoyed.