PowerShell For The .NET Developer

Some time ago I needed to have the validationKey of the machineKey element of an ASP.NET application changed and found out that ASP.NET doesn’t provide a command-line tool (or any other) to do this.

Looking around I found several applications and code samples to do it, but to have a system administrator do this I needed to test and document the application and it was to much work for such task.

I’ve always been a supporter of the idea of PowerShell but I never used it my self. Just because I almost always have Visual Studio open and writing a simple console application is quicker and easier than learning PowerShell.

This time I decide that I would do a PowerShell script instead.

In C# I would have done something like this:

class Program
    private static string GenerateKey()
        var buff = new byte[64];
        (new System.Security.Cryptography.RNGCryptoServiceProvider()).GetBytes(buff);
        var sb = new System.Text.StringBuilder();
        foreach (var b in buff)
            sb.AppendFormat("{0:X2}", b);
        return sb.ToString();

    private static void Main(string[] args)
        var path = args[0];
        var config = System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration(path);
        var systemWeb = config.GetSectionGroup("system.web") as System.Web.Configuration.SystemWebSectionGroup;
        var machineKey = systemWeb.MachineKey;
        machineKey.ValidationKey = GenerateKey();

How would it be in PowerShell? As simple as this:

function GenerateKey
    [System.Byte[]]$buff = 0..63
    (new-object System.Security.Cryptography.RNGCryptoServiceProvider).GetBytes($buff)
    $sb = new-object System.Text.StringBuilder(128)
    for($i = 0; ($i -lt $buff.Length); $i++)
        $sb = $sb.AppendFormat("{0:X2}", $buff[$i])
    return $sb.ToString()

$config = [System.Web.Configuration.WebConfigurationManager]::OpenWebConfiguration("<path>")
$systemWeb = $config.GetSectionGroup("system.web");
$machineKey = $systemWeb.MachineKey

Wonder how I got from no knowledge of PowerShell to this? Simple. Something that every real .NET developer has and loves: .NET Reflector (with a PowerShell add-in, of course).