How-to: Retrieve the Windows Product Key

The Windows product key is a 25-character code used to activate Windows. In most cases, Windows 10 activates automatically using a digital license and doesn't require you to enter a product key.

function Get-WindowsProductKey{
    Param(
        [string]$computer=$env:COMPUTERNAME
    )
    
    $Reg = [WMIClass] ("\\" + $computer + "\root\default:StdRegProv")
    $values = [byte[]]($reg.getbinaryvalue(2147483650,"SOFTWARE\Microsoft\Windows NT\CurrentVersion","DigitalProductId").uvalue)
    $lookup = [char[]]("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9")
    $keyStartIndex = [int]52;
    $keyEndIndex = [int]($keyStartIndex + 15);
    $decodeLength = [int]29
    $decodeStringLength = [int]15
    $decodedChars = new-object char[] $decodeLength
    $hexPid = new-object System.Collections.ArrayList
    for ($i = $keyStartIndex; $i -le $keyEndIndex; $i++){ [void]$hexPid.Add($values[$i]) }
    for ( $i = $decodeLength - 1; $i -ge 0; $i--)
        {                
         if (($i + 1) % 6 -eq 0){$decodedChars[$i] = '-'}
         else
           {
            $digitMapIndex = [int]0
            for ($j = $decodeStringLength - 1; $j -ge 0; $j--)
            {
                $byteValue = [int](($digitMapIndex * [int]256) -bor [byte]$hexPid[$j]);
                $hexPid[$j] = [byte] ([math]::Floor($byteValue / 24));
                $digitMapIndex = $byteValue % 24;
                $decodedChars[$i] = $lookup[$digitMapIndex];
             }
            }
         }
    $STR = ''    
    $decodedChars | % { $str+=$_}
    return $str

}
Get-WindowsProductKey

Example

$mykey = Get-WindowsProductKey

“I can always guess how many jelly beans are in a jelly bean jar, even if I'm wrong” ~ Anchorman.

Related PowerShell Cmdlets:

DISM /Set-ProductKey - Set the product key of an offline image.
SLMGR - Software Licensing Management Tool Activate Windows license and product key.


 
Copyright © 1999-2021 SS64.com
Some rights reserved