我有一个有效的 powershell 脚本,可以从我们网络中的一台机器上获取 Windows 产品密钥。该脚本在 powershell 命令行中运行良好,但当我尝试从 C# 运行它时返回错误。我需要这项工作来绘制我们公司的许可证。
电源外壳代码:
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
只需将 $server 替换为 . 或您的 IP
运行脚本的 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 += " ";
}
}
如果可以的话请帮忙。我已经知道错误是在 C# GetBinaryValue 中返回 null。我就是不能让它工作。