Get license key of a SQL server installation

# PowerShell Script

Set-PSDebug -Off  

function Get-SQLserverKey {
    param ($targets = ".")

    $hklm      = 2147483650    # HKEY_LOCAL_MACHINE
    $regPath   = "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL17.MSSQLSERVER\Setup"    # replace this with matched reg path
    $regValue1 = "DigitalProductId"
    $regValue2 = "PatchLevel"
    $regValue3 = "Edition"

    foreach ($target in $targets) {
        $productKey = $null
        $win32os    = $null
        $wmi        = [WMIClass]"\\$target\root\default:stdRegProv"

        $data        = $wmi.GetBinaryValue($hklm, $regPath, $regValue1)
        [string]$SQLver     = $wmi.GetStringValue($hklm, $regPath, $regValue2).sValue
        [string]$SQLedition = $wmi.GetStringValue($hklm, $regPath, $regValue3).sValue

        $binArray   = ($data.uValue)[0..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"

        $isNKey = ([math]::Truncate($binArray[14] / 0x6) -band 0x1) -ne 0
        if ($isNKey) {
            $binArray[14] = $binArray[14] -band 0xF7
        }

        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
            $last       = $k
        }

        if ($isNKey) {
            $part1 = $productKey.Substring(1, $last)
            $part2 = $productKey.Substring(1, $productKey.Length - 1)

            if ($last -eq 0) {
                $productKey = "N" + $part2
            } else {
                $productKey = $part2.Insert($part2.IndexOf($part1) + $part1.Length, "N")
            }

            $productKey = $productKey.Insert(20, "-").Insert(15, "-").Insert(10, "-").Insert(5, "-")
        }

        $win32os = Get-WmiObject Win32_OperatingSystem -Computer $target

        $obj = New-Object Object
        $obj | Add-Member NoteProperty Computer    -Value $target
        $obj | Add-Member NoteProperty OSCaption   -Value $win32os.Caption
        $obj | Add-Member NoteProperty OSArch      -Value $win32os.OSArchitecture
        $obj | Add-Member NoteProperty SQLver      -Value $SQLver
        $obj | Add-Member NoteProperty SQLedition  -Value $SQLedition
        $obj | Add-Member NoteProperty ProductKey  -Value $productKey

        $obj
    }
}

Get-SQLserverKey
创建时间:9/5/2026 11:47:47 AM 修改时间:9/5/2026 11:49:15 AM