我正在使用一些PowerShell functions来配置Windows产品密钥和激活。我得到SoftwareLicensingService
的一个实例,然后调用InstallProductKey
,就像这样。具有超级格式的trap
块是额外的,以帮助调试。
trap [Exception]
{
"=================================================="
"Trapped: $($Error[0])"
"=================================================="
"Exception: $($_.Exception)"
"--------------------------------------------------"
""
break
}
$service = Get-WmiObject -Query "SELECT * FROM SoftwareLicensingService"
$service.InstallProductKey("12345-12345-12345-12345-12345")
$service.RefreshLicenseStatus() | Out-Null
错误情况是无效的产品密钥。我知道这是因为我从 System 面板手动输入 Activate Windows 对话框。但是,该脚本只向我显示WMIMethodException
或COMException
。
==================================================
Trapped: Exception calling "InstallProductKey" : ""
==================================================
Exception: System.Runtime.InteropServices.COMException (0xC004F025)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Management.ManagementObject.InvokeMethod(String methodName, ManagementBaseObject inParameters, InvokeMethodOptions options)
at System.Management.Automation.ManagementObjectAdapter.InvokeManagementMethod(ManagementObject obj, String methodName, ManagementBaseObject inParams)
--------------------------------------------------
Exception calling "InstallProductKey" : ""
At line:14 char:31
+ $service.InstallProductKey <<<< ("12345-12345-12345-12345-12345")
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : WMIMethodException
我没有从方法中获得返回代码(尽管文档说明我做了,但无论如何都找不到错误代码列表)。 您知道如何获得激活(或产品密钥安装)错误原因吗?
答案 0 :(得分:1)
据我所知,那里没有任何消息。将这些添加到您的陷阱:
$_ | fl * -Force
$_.Exception | fl * -Force
返回异常中的所有内容,没有任何用处。所以我用谷歌搜索了一下,在这里发现了一段C#代码:http://www.dozty.com/?tag=change-windows-7-product-key-c-sharp他们正在使用ManagementException,而在C#中它似乎工作得更好一些。我已将该代码重写为PowerShell并试图捕获ManagementException,但没有运气:
trap [Exception]
{
[System.Management.ManagementException] $_
break
}
$classInstance = new-object System.Management.ManagementObject("root\CIMV2","SoftwareLicensingService.Version=`"6.1.7600.16385`"", $null);
$inParams = $classInstance.GetMethodParameters("InstallProductKey")
$inParams["ProductKey"] = "12345-12345-12345-12345-12345"
$classInstance.InvokeMethod("InstallProductKey", $inParams, $null)
它抛出:无法转换“System.Runtime.InteropServices.COMException(0xC004F050)”