PowerShell – Return Product Key and/or Save to Text File

email me

Function Get-ProductKey
{   Clear-Host
	$HKLM = 2147483650
	$ComputerName = $env:COMPUTERNAME
	$MSRegPath = "Software\Microsoft\Windows NT\CurrentVersion"
	$DigitalID = "DigitalProductId"
	$wmi = [WMIClass]"\\$ComputerName\root\default:stdRegProv"
	#Return MS Reg Value - used in translation
	$WMIObject = $wmi.GetBinaryValue($HKLM,$MSRegPath,$DigitalID)
	[Array]$DigitalValue = $WMIObject.uValue 
	#If value is returned
	If($DigitalValue)
	{		
		#Perform translation 
		$TranslatedResult = ConvertTokey $DigitalValue
		$OperatingSystem = (Get-WmiObject "Win32_OperatingSystem"  | select Caption).Caption
		If($OperatingSystem -match "Microsoft Windows 8" -or $OperatingSystem -match "Microsoft Windows 10")
		{
			if($TranslatedResult)
			{
				
				[string]$ProductKey ="$TranslatedResult"
				$ProductKey 
				#Save Windows info to a file 
				$UserChoice = UserOption
				If( $UserChoice -eq 0 )
				{	
					$TextFilePath = "C:\Users\"+$env:USERNAME+"\Desktop"
					New-Item -Path $TextFilePath -Name "ProductKey.txt" -Value $ProductKey -ItemType File -Force | Out-Null 
                    
				}                			
			}
			
		}	
		
	}
	

}
#User Option 
Function UserOption
{
    $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes",""
    $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No",""
    $UserChoices = [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no)
    $MsgCaption = "Confirm"
    $Msg = "  Save product key to ProductKey.txt on Desktop?"
    $TranslatedResult = $Host.UI.PromptForChoice($MsgCaption,$Msg,$UserChoices,0)
    $TranslatedResult
}
#Perform translation 
Function ConvertToKey($Key)
{
	$Keyoffset = 52 
	$isWin8 = [int]($Key[66]/6) -band 1
	$HF7 = 0xF7
	$Key[66] = ($Key[66] -band $HF7) -bOr (($isWin8 -band 2) * 4)
	$i = 24
	[String]$Chars = "BCDFGHJKMPQRTVWXY2346789"	
	do
	{
		$Cur = 0 
		$X = 14
		Do
		{
			$Cur = $Cur * 256    
			$Cur = $Key[$X + $Keyoffset] + $Cur
			$Key[$X + $Keyoffset] = [math]::Floor([double]($Cur/24))
			$Cur = $Cur % 24
			$X = $X - 1 
		}while($X -ge 0)
		$i = $i- 1
		$KeyOutput = $Chars.SubString($Cur,1) + $KeyOutput
		$last = $Cur
	}while($i -ge 0)
	
	$Keypart1 = $KeyOutput.SubString(1,$last)
	$Keypart2 = $KeyOutput.Substring(1,$KeyOutput.length-1)
	if($last -eq 0 )
	{
		$KeyOutput = "N" + $Keypart2
	}
	else
	{
		$KeyOutput = $Keypart2.Insert($Keypart2.IndexOf($Keypart1)+$Keypart1.length,"N")
	}
	$a = $KeyOutput.Substring(0,5)
	$b = $KeyOutput.substring(5,5)
	$c = $KeyOutput.substring(10,5)
	$d = $KeyOutput.substring(15,5)
	$e = $KeyOutput.substring(20,5)
	$keyproduct = $a + "-" + $b + "-"+ $c + "-"+ $d + "-"+ $e
	$keyproduct 
	
  
}
Get-ProductKey