Click here to Skip to main content
15,867,949 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello.

I have a working powershell script to get the Windows product key from an machine in our network. The script runs well in powershell comand line but returns error when I try to run it from C#. I need this working to chart licenses in our corporation.

Powershell code:
PHP
function Get-WindowsKey {
    $target = '$server'
    $hklm = 2147483650
    $regPath = "Software\Microsoft\Windows NT\CurrentVersion\DefaultProductKey"
    $regValue = "DigitalProductId4"
    $productKey = $null
    $win32os = $null
    $wmi = [WMIClass]"\\$target\root\default:stdRegProv"
    $data = $wmi.GetBinaryValue($hklm,$regPath,$regValue)
    $binArray = ($data.uValue)[52..66]
    $charsArray = "B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9"
    For ($i = 24; $i -ge 0; $i--) {
        $k = 0
        For ($j = 14; $j -ge 0; $j--) {
            $k = $k * 256 -bxor $binArray[$j]
            $binArray[$j] = [math]::truncate($k / 24)
            $k = $k % 24
        }
        $productKey = $charsArray[$k] + $productKey
        If (($i % 5 -eq 0) -and ($i -ne 0)) {
            $productKey = "-" + $productKey
        }
    }
    $productkey
}
Get-WindowsKey | Format-Table -AutoSize



C# code that runs script:
C#
private void RunWindowsKeyScript(string IP)
        {
            try
            {
                Assembly Keyassembly = this.GetType().Assembly;
                ResourceManager Keyresman = new ResourceManager("LanMap.Resources.PS script", Keyassembly);
                string KeyScript = Keyresman.GetString("WindowsKey");
                KeyScript = KeyScript.Replace("$server", IP);

                Runspace Keyrunspace = RunspaceFactory.CreateRunspace();
                Keyrunspace.Open();
                Pipeline Keypipeline = Keyrunspace.CreatePipeline();
                Keypipeline.Commands.AddScript(KeyScript);
                Keypipeline.Commands.Add("Out-String");
                Collection<psobject> Keyresults = Keypipeline.Invoke();
                Keyrunspace.Close();
                StringBuilder KeystringBuilder = new StringBuilder();
                foreach (PSObject obj in Keyresults)
                {
                    KeystringBuilder.AppendLine(obj.ToString());
                }
            }
            catch (Exception ex)
            {
                string s = "";
                s += " ";
            }
        }

Please help if you can. I already know the error is that in C# GetBinaryValue returns null. I just can not make it work.
Posted
Updated 27-Jan-13 21:31pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900