Cannot retrieve windows product key using VBA - Au

2019-07-08 03:38发布

问题:

The following code throws an 'Automation Error'

Sub GetWindowsProductKey()

Set WshShell = CreateObject("WScript.Shell")
MsgBox WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId")

End Sub

But this code works fine

Sub GetPath()

Set WshShell = CreateObject("WScript.Shell")
MsgBox WshShell.RegRead("HKEY_CURRENT_USER\Environment\Path")

End Sub

Clearly this has something to do with the product key being protected or something.

I'm writing a spreadsheet to collect auditing data from remote offices before anyone assumes I'm (really bad at) hacking.


UPDATE

I'm now trying the following approach, but I'm getting a type mismatch error instead on the second function (the first one still works) ...

Sub GetPathUsingStdRegProv()

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."

Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")

strKeyPath = "Environment"
strValueName = "Path"

oReg.GetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strValue

MsgBox strValue

End Sub

Sub GetWindowsKeyUsingStdRegProv()

Const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."

Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")

strKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
strValueName = "DigitalProductId"

oReg.GetBinaryValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue

For i = LBound(strValue) To UBound(strValue)
    MsgBox strValue(i)
Next

End Sub

strValue is Null in the second function, which explains the type mismatch!!


Update 2

I've use the code from this SO question, along with

ShellRun("wmic path softwarelicensingservice get OA3xOriginalProductKey")

which works on my laptop, but not on one of the desktops, presumably because the key isn't stored in BIOS/UEFI. So I'm still looking for a solution!


update 3

I've executed the code in the answer below as a vbs script, but the value I get on my laptop is different to the one i got from wmic technique above?! Is that a 64-bit issue? This is all very confusing!!

标签: excel vba wsh