hits counter

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();
    }
<span style="color: blue">private static void </span>Main(<span style="color: blue">string</span>[] args)
{
    <span style="color: blue">var </span>path = args[0];
    <span style="color: blue">var </span>config = System.Web.Configuration.<span style="color: #2b91af">WebConfigurationManager</span>.OpenMachineConfiguration(path);
    <span style="color: blue">var </span>systemWeb = config.GetSectionGroup(<span style="color: #a31515">&quot;system.web&quot;</span>) <span style="color: blue">as </span>System.Web.Configuration.<span style="color: #2b91af">SystemWebSectionGroup</span>;
    <span style="color: blue">var </span>machineKey = systemWeb.MachineKey;
    machineKey.ValidationKey = GenerateKey();
    config.Save(System.Configuration.<span style="color: #2b91af">ConfigurationSaveMode</span>.Modified);
}

}

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()
}

[System.Reflection.Assembly]::LoadWithPartialName("System.Web")
$config = [System.Web.Configuration.WebConfigurationManager]::OpenWebConfiguration("<path>")
$systemWeb = $config.GetSectionGroup("system.web");
$machineKey = $systemWeb.MachineKey
$machineKey.ValidationKey=GenerateKey
$config.save("Modified")

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).

1 Comment

Comments have been disabled for this content.