Mailing List



NerdyHearn - Blog

<< Back To All Blogs

Programatically Retrieving an Assembly's PublicKeyToken through a PowerShell CmdLet

Wednesday, April 15th, 2009

While doing SharePoint development and deployment, you are constantly on the lookout for the Public Key Token of the assembly you will be deploying to SharePoint as it has to be set as a Safe Assembly, and in order to do this you need to know the Public Key Token. To automate this process better, and in my continual quest to move my entire development process to PowerShell, I decided it was time to write a cmdlet to get me the Public Key token of an assembly, as the SN.exe tool provided by Microsoft doesn't give you an easy option of getting just the Public Key token (it has a bunch of literals around it).

So without further ado, here is the code for the cmdlet:

using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.IO;
using System.Runtime;
using System.Reflection;

namespace NerdyHearn.Com.PowerShell
[Cmdlet(VerbsCommon.Get, "PublicKeyToken", SupportsShouldProcess=true)]
public class GetPublicKeyToken : PSCmdlet
private string m_AssemblyPath = string.Empty;

[Parameter(Mandatory = true,
HelpMessage = "The path to the file you wish to obtain the Public Key Token.")]
public string AssemblyPath
return m_AssemblyPath;
m_AssemblyPath = value;

protected override void BeginProcessing()
Assembly assembly = Assembly.LoadFrom(SessionState.Path.CurrentFileSystemLocation.Path + "\" + m_AssemblyPath);
byte []pt = ass.GetName().GetPublicKeyToken(); // This give the key in a byte array
string key = string.Empty;
for (int a=0; a<pt.Length; a++) {
key += String.Format("{0:x}", pt[a]); // Convert the byte-array to a human-readable string
catch (Exception ex)

Very simple, but also very useful. To use this cmdlet above you would have to build it, install it with InstallUtil, and add it with add-pssnapin.

Calling the script is simple: Get-PublicKeytoken -AssemblyPath My.Assembly.dll

Please note that this will not work with PowerShell PSDrives.

I'm one step closer to being completely PowerShell in builds...

Shellin' Tom Out.


CSharp PowerShell

Related Blogs

Reading Digital Signatures from InfoPath Forms in MOSS 2007 and WSS 3.0 Workflow
Writing console output from a Windows form in C#

Retrieving Text from Win32 SDK's GetLastError() in C#


Tom Hearn said on Friday, April 17th, 2009 @ 2:18 PM

Thanks Joe, very nice!

Joe Pruitt said on Friday, April 17th, 2009 @ 2:13 PM

I just put a script function version on my blog that's equivalent to your Cmdlet.

Add A Comment



Email Address: (not public, used to send notifications on further comments)


Enter the text above, except for the 1st and last character:

NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers