PowerShell Cmdlets sources

Sometime you want to understand how exactly PowerShell cmdlets work.

And fortunately we can see exact source code for them in a Reflector

Inspired by the this, I wrote the following script Reflect-Cmdlet.ps1

#requires -version 2

param(
    [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName="Command")]
    [Management.Automation.CommandInfo] $Command,

    [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName="CommandName")]
    [string] $CommandName
)

# TODO: use path to your Reflector instead
$reflectorPath = "c:\Work\Tools\Reflector\Reflector.exe"

if ($CommandName) {
    $Command = Get-Command $CommandName
}

while ($Command.CommandType -eq "Alias") {
    "Command '$($Command.Name)' is an alias for command '$($Command.Definition)'"
    $Command = Get-Command $Command.Definition
}

switch ($Command.CommandType) {
    "Cmdlet" {
        $type = $Command.ImplementingType
        $dll = $Command.DLL
        if (-not (Test-Path $reflectorPath)) {
            throw "Reflector is not found in '$reflectorPath'"
        }

        & $reflectorPath /select:$type $dll
    }
    "Function" {
        "Command '$($Command.Name)' is a function with the following definition:`n`n$($Command.Definition)"
    }
    default {
        "Command '$($Command.Name)' has an unsupported type $($Command.CommandType)"
    }
}

Now it can be used in a lot of ways

Reflect-Cmdlet "Write-Host"

"Write-Debug" | Reflect-Cmdlet

Get-Command cls | Reflect-Cmdlet
Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s