Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@JPRuskin
Last active April 5, 2020 11:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JPRuskin/9caf8ee0d4dd000bea0b98a329e1f2d1 to your computer and use it in GitHub Desktop.
Save JPRuskin/9caf8ee0d4dd000bea0b98a329e1f2d1 to your computer and use it in GitHub Desktop.
Should output the Windows product key
function ConvertTo-ProductKey {
[CmdletBinding()]
param(
[byte[]]$Key,
[switch]$Validate
)
end {
$KeyOffset = 52
[char[]]$Chars = "BCDFGHJKMPQRTVWXY2346789"
$KeyOutput = ""
[int]$isWin8 = ($Key[66] / 6) -and 1
$Key[66] = ($Key[66] -and 247) -or (($IsWin8)*4)
for ($i = 24; $i -ge 0; $i--) {
[int]$Current = 0
for ($x = 14; $x -ge 0; $x--) {
$Current = $Current * 256
$Current += $Key[$X + $KeyOffset]
$Key[$X + $KeyOffset] = [math]::floor($Current / 24)
$Current = $Current % 24
}
$KeyOutput = "$($Chars[$Current])$($KeyOutput)"
}
if ($isWin8) {
$ReplaceString = -join $KeyOutput[1..$Current]
$KeyOutput = (-join $KeyOutput[1..$KeyOutput.Length]) -replace "^$ReplaceString", "$($ReplaceString)N"
if ($Current -eq 0) {$KeyOutput = "N$($KeyOutput)"}
}
@(
$KeyOutput.Substring(0,5)
$KeyOutput.Substring(5,5)
$KeyOutput.Substring(10,5)
$KeyOutput.Substring(15,5)
$KeyOutput.Substring(20,5)
) -join '-'
if ($Validate) {
$LastGroupShouldBe = (Get-CimInstance -Query 'Select PartialProductKey From SoftwareLicensingProduct Where Name LIKE "Windows%" AND LicenseStatus>0').PartialProductKey
if ($LastGroupShouldBe -eq $KeyOutput.Substring(20,5)) {
Write-Information "Calculated key matches PartialProductKey '$($LastGroupShouldBe)'"
} else {
Write-Error "Calculated key did not match PartialProductKey '$($LastGroupShouldBe)'"
}
}
}
}
$RegPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\"
[byte[]]$DigitalProductIDBytes = Get-ItemProperty $RegPath -Name DigitalProductId | % DigitalProductId
@{
ProductName = Get-ItemProperty $RegPath -Name ProductName | % ProductName
ProductID = Get-ItemProperty $RegPath -Name ProductID | % ProductID
ProductKey = ConvertTo-ProductKey -Key $DigitalProductIDBytes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment