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