How to detect if Powershell is installed - C#

I recently found myself in a situation where I assumed Powershell was installed on a Windows server (after all, Powershell is installed on every Windows server, surely?), and it wasn't.

Thus, calling a Powershell script from C# caused quite a few errors, and taught me to always check if Powershell is available before using it.

Fortunately, there's an easy way to do it!

Detecting Powershell from the registry

In C#, if we know the registry path and the key name, we can grab the associated value from the registry using:

Microsoft.Win32.Registry.GetValue("path-goes-here", "key-name-goes-here")

In our case, we want to find the Install key, in the path:

public bool IsPowershellInstalled()
    string val = Microsoft.Win32.Registry
        .GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1", "Install")

    return val.Equals("1");

It's a simple method, but very useful for preventing bugs that might otherwise only be found in production!