PoshCode Archive  Artifact [42ad97a5ac]

Artifact 42ad97a5acdf155b2735f19b78f1a0df7e1caec07416ac94609bbca03db9402c:

  • File get-windows-product-key.ps1 — part of check-in [d977d38fd2] at 2018-06-10 13:46:03 on branch trunk — hey guys. why you duplicate ugly code for retrieving product key? everything can be done much easier. (user: greg zakharov size: 1084)

# encoding: ascii
# api: powershell
# title: get windows product key
# description: hey guys. why you duplicate ugly code for retrieving product key? everything can be done much easier.
# version: 0.1
# type: function
# author: greg zakharov
# license: CC0
# function: Get-ProductKey
# x-poshcode-id: 4802
# x-archived: 2014-01-21T02:09:40
# x-published: 2014-01-16T16:20:00
#
#
function Get-ProductKey([String]$Computer = '.') {
  begin {
    $val = [Byte[]]([wmiclass]('\\' + $Computer + '\root\default:StdRegProv')).GetBinaryValue(
      2147483650, 'SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'DigitalProductId'
    ).uValue[52..66]
    $map = "BCDFGHJKMPQRTVWXY2346789"
    $key = ""
  }
  process {
    for ($i = 24; $i -ge 0; $i--) {
      $k = 0
      for ($j = 14; $j -ge 0; $j--) {
        $k = ($k * 256) -bxor $val[$j]
        $val[$j] = [Math]::Floor([Double]($k / 24))
        $k = $k % 24
      }
      $key = $map[$k] + $key
      if (($i % 5) -eq 0 -and $i -ne 0) {$key = "-" + $key}
    }
  }
  end {$key}
}

Get-ProductKey