Workable Solutions | Step-by-step Troubleshooting |
---|---|
Fix 1. Key Finder | Click «Windows» tab under the Registry Key…Full steps |
Fix 2. CMD | Open a new Administrator Command Prompt window in Windows…Full steps |
Fix 3. Powershell | If you’re using Windows 10 PowerShell, the steps are the same as before…Full steps |
Fix 4. Registry | Select «Run» from the Windows «Start» menu. Press the «Ok» button after typing «Regedit»…Full steps |
How Do I Find My Windows Server 2012 Product Key
Before the era of cloud computing, Windows Server 2012 R2 was widely recognized as one of the best enterprise server software of its time, with numerous capabilities that you can use for personal or professional purposes. Because it’s a Windows operating system, you’ll need a valid product key to activate and use it. It will be in a trial state if you don’t have it, so you won’t be able to use it to its total capacity.
However, obtaining a product key for Windows Server 2012 R2 is simple. We’ll show you three ways to find the Windows Server 2012 Product Key in this guide.
- 1. Make use of the Windows Product Key Finder program.
- 2. Use PowerShell/Command Prompt
- 3. Make use of the registry
#1. Find Windows Server 2012 Product Key Using Windows Product Key Finder
The best product key finder in 2023 is EaseUS Key Finder, a Windows product key finder app. It actually has excellent functionality for locating product keys for Windows OS and installed software.
Our first technique for locating a Windows Server 2012 product key is to use EaseUS Key Finder. It’s relatively simple to use and works with all Windows Server and Microsoft SQL Server versions.
If you replace your PC’s hard disc, you’ll have to reinstall and reactivate Windows or Office on your new machine. It takes a long time to locate activation keys! Is there any way to get the product keys quickly? EaseUS Key Finder is a sophisticated key finder software. EaseUS Key Finder is a handy tool that shows you the ProductIDs and CD-Keys for Windows and SQL Server, Microsoft Office, Adobe, and other programs that are installed on your computer. WiFi codes, browser accounts, and passwords can all be found here.
Step 1. Click «Windows» tab under the Registry Key.
Step 2. Check Windows product key on the right side. Click «Copy» to paste. Or select other two options:
«Save» — Save to local as a PDF file.
«Print» — Click to print key file.
Features
- Retrieve Windows System Product Keys
- Recover Office, Adobe Product Keys
- Recover Passwords Saved in Web Browsers: Chrome, Edge, Firefox, and Internet Explorer
- Recover Windows Credentials
- Get 1000+ Software Serials
- Find WiFi Passwords
Pros
- Find key support for Windows 11/10/8/7 and Windows Vista/XP.
- Support for locating saved accounts and passwords in browsers such as Chrome, IE, Edge, Firefox, etc.
- 1-click to find the product key
- Browsers such as Chrome, IE, Edge, Firefox, and others can be used to locate saved accounts and passwords.
- Ads-free, virus-free.
Cons
- Requires activation for unlocking full features.
Why Choose EaseUS Key Finder
The three most important advantages of utilizing EaseUS Key Finder are:
- Backup Activation Keys
- Recover Key from Dead OS/Disks
- Technical Support
Backup Activation Keys
Finding product keys can be time and money-consuming. You can save your product keys to a PDF document or copy them into a Text file.
Recover Key from Dead OS/Disks
EaseUS Key Finder can scan product keys from an unbootable hard disc drive (HDD/SSD) or another dead Windows operating system.
Technical Support
Get in touch with EaseUS! The EaseUS technical support team provides flexible, round-the-clock technical support, assisting customers with quick and competent solutions.
#2. Find Windows Server 2012 Product Key Using CMD/PowerShell
Find Windows Server 2012 Product Key Using CMD
Turning to a privileged command prompt in Windows and running a command that retrieves the software licensing product key is the most straightforward approach to find the Windows Product Key license.
Step 1. Open a new Administrator Command Prompt window in Windows.
Step 2. After you’ve opened the cmd, type the following:
wmic path softwarelicensingservice get OA3xOriginalProductKey
Step 3. To see the Windows product key, press Enter and Return. It’s a 25-character alphanumeric string with the following format:
XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
That is all there is to it. This procedure can be used to obtain the Windows product key on practically any Windows installation.
Recover the Lost Server Product Key in Powershell
Step 1. If you’re using Windows 10 PowerShell, the steps are the same as before. Select Windows PowerShell (Admin) from the context menu after right-clicking the Start Menu button.
Step 2. At the prompt, enter this command to reveal the product key, as shown in Figure.
PowerShell «(Get-WmiObject -query ‘select * from SoftwareLicensingService’).OA3xOriginalProductKey
Step 3. Wait a few moments for PowerShell to display the licensing key for your current Windows operating system version.
#3. Find Windows Server 2012 Product Key in Registry
A product license key is an input into the installation wizard each time you install Windows. The Windows registry stores this key. Each time you load a Windows update, the product license is saved in the registry and reviewed. If the product key is invalid, you may have difficulty accessing certain operating system capabilities, and updates may be denied. If you’ve misplaced the packing, looking up the product ID in the registry will help you find it.
Step 1. Select «Run» from the Windows «Start» menu. Press the «Ok» button after typing «Regedit» into the text field. The Windows registry editor will open as a result of this.
Step 2. In the registry, look for the «HKEY LOCAL MACHINESOFTWAREMicrosoftWindowsCurrentVersion» key. This folder contains a variety of Windows-related configuration files for your machine.
Step 3. When you right-click the «ProductId» key, choose «Modify» from the context menu. Look at the displayed number. This is your Windows product key. To avoid changing the value, press the «Cancel» button.
Conclusion
All of the ways for locating a Windows Server 2008 product key listed are simple. The product keys for your operating system and other vital programs can be presented to you with only a few clicks.
However, you must select a preferred option, and we propose EaseUS Key Finder. It’s our top pick because we’ve tried it and can vouch for its effectiveness. It not only assists you in locating the Windows Server 2008 product key but also provides numerous other benefits.
Что делать если вы забыли ключ от Windows 10 или Windows 8? Как быть если предыдущий администратор не передал вам ключ от Windows Server 2012 R2? Ноутбук с Windows непонятной версии нужно откатить на заводские настройки, а ключ от операционной системы никто не помнит?
В зависимости от того, как вы получили свою копию Windows 10, для активации может потребоваться 25-значный ключ продукта или цифровая лицензия.
- Цифровая лицензия (в Windows 10 версии 1511 носит название цифрового разрешения) — это способ активации в Windows 10, который не требует ввода ключа продукта.
- Ключ продукта представляет собой 25-значный код, используемый для активации Windows. Вы увидите КЛЮЧ ПРОДУКТА: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX.
Ключ продукта
Если у вас установлен ключ продукта, то можно его узнать. Просто скопируйте текст ниже в файл winkey.vbs и запустите на нужной машине. Если повезёт, то скрипт определит ключ и версию системы.
Ключ продукта в BIOS
Лицензионный ключ может быть прописан в BIOS устройства. Узнать его можно через Powershell:
(Get-WmiObject -query 'select * from SoftwareLicensingService').OA3xOriginalProductKey
Или в командной строке:
wmic path softwarelicensingservice get OA3xOriginalProductKey
Цифровая лицензия
Если вы бесплатно обновили ОС Windows 7 или Windows 8.1 до Windows 10, вместо ключа продукта вы должны получить цифровую лицензию. Если у вас есть цифровая лицензия для устройства, вы можете переустановить тот же выпуск Windows 10 на этом устройстве без ввода ключа продукта.
В этом случае при попытке запустить скрипт для определения ключа вы получите это: BBBBB-BBBBB-BBBBB-BBBBB-BBBBB.
Открываем окно параметров.
Проверить состояния активации в параметрах
Надпись об активации может отличаться:
Ключ по умолчанию
Можно узнать ключ по умолчанию для текущей редакции. Он устанавливается, если вы не указываете свой ключ и сохраняется при получении цифровой лицензии.
Частично:
slmgr -dli
slmgr -dlv
Полную версия ключа можно посмотреть в реестре:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProtectionPlatform\BackupProductKeyDefault
Скрипт VBS в помощь. Просто скопируйте текст ниже в файл winkey2.vbs и запустите на нужной машине. Скрипт определит ключ по умолчанию и версию системы.
Этот ключ позволит установить windows 10 без проведения активации. Потом автоматически должна активироваться цифровая лицензия, если она привязана к вашей учётной записи Microsoft.
- Remove From My Forums
-
Question
-
Hi Team,
We have activated Windows Server 2012 standard. We are planing to format it . So we want to get it product or CD-key . Is any tool or command is available to find its key.
All replies
-
Hi,
Open Notepad.
Copy and paste the following text into the notepad windowfunction Get-WindowsKey {
## function to retrieve the Windows Product Key from any PC
## by Jakob Bindslet (jakob@bindslet.dk)
param ($targets = «.»)
$hklm = 2147483650
$regPath = «Software\Microsoft\Windows NT\CurrentVersion»
$regValue = «DigitalProductId»
Foreach ($target in $targets) {
$productKey = $null
$win32os = $null
$wmi = [WMIClass]»\\$target\root\default:stdRegProv»
$data = $wmi.GetBinaryValue($hklm,$regPath,$regValue)
$binArray = ($data.uValue)[52..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″
## decrypt base24 encoded binary data
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
If (($i % 5 -eq 0) -and ($i -ne 0)) {
$productKey = «-» + $productKey
}
}
$win32os = Get-WmiObject Win32_OperatingSystem -computer $target
$obj = New-Object Object
$obj | Add-Member Noteproperty Computer -value $target
$obj | Add-Member Noteproperty Caption -value $win32os.Caption
$obj | Add-Member Noteproperty CSDVersion -value $win32os.CSDVersion
$obj | Add-Member Noteproperty OSArch -value $win32os.OSArchitecture
$obj | Add-Member Noteproperty BuildNumber -value $win32os.BuildNumber
$obj | Add-Member Noteproperty RegisteredTo -value $win32os.RegisteredUser
$obj | Add-Member Noteproperty ProductID -value $win32os.SerialNumber
$obj | Add-Member Noteproperty ProductKey -value $productkey
$obj
}
}Save the text above into a file with the «.ps1» extension on the Desktop. Exemple key.ps1
Open the Powershell console as administrator and type in Set-ExecutionPolicy RemoteSigned
Next type in Import-Module C:\users\»username»\desktop\key.ps1; Get-WindowsKey
And that’s it
-
Edited by
Wednesday, February 15, 2017 12:38 PM
-
Proposed as answer by
Leo Han
Thursday, March 9, 2017 11:07 AM
-
Edited by
-
Hi Team,
We have actived Windows server 2012 standard.We are planing to format it, Is any tool or command is available to know its CD or product key so that we can active it again .
-
Merged by
Leo Han
Thursday, February 16, 2017 6:41 AM
duplicated
-
Merged by
-
HI.
You can simply run below command in command prompt as administrator
wmic path softwarelicensingservice get OA3xOriginalProductKey
Thanks
Mahipal Singh
-
after following above command it is giving me below error
C:\users\»username»\desktop\key.ps1; Get-WindowsKey is not recognized as the name of a cmdlet, function, scrip file, or operable program.
-
This one might help.
http://www.nirsoft.net/utils/product_cd_key_viewer.html
Regards, Dave Patrick ….
Microsoft Certified Professional
Microsoft MVP [Windows Server] Datacenter ManagementDisclaimer: This posting is provided «AS IS» with no warranties or guarantees, and confers no rights.
-
Proposed as answer by
Leo Han
Thursday, March 9, 2017 11:07 AM
-
Proposed as answer by
-
Hi Dave,
I have windows server 2012 R2 Standard
-
Getting below error.
Import-Module : The specified module ‘C:\users\administrator\desktop\key.ps1’ was not loaded because no valid module
file was found in any module directory.
At line:1 char:1
+ Import-Module C:\users\»administrator»\desktop\key.ps1; Get-WindowsKey
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (C:\users\administrator\desktop\key.ps1:String) [Import-Module], Fi
leNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommandGet-WindowsKey : The term ‘Get-WindowsKey’ is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:57
+ Import-Module C:\users\»administrator»\desktop\key.ps1; Get-WindowsKey
+ ~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-WindowsKey:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException -
Hi Dave,
I have windows server 2012 R2 Standard
Yes, it works fine.
Regards, Dave Patrick ….
Microsoft Certified Professional
Microsoft MVP [Windows Server] Datacenter ManagementDisclaimer: This posting is provided «AS IS» with no warranties or guarantees, and confers no rights.
-
From a PowerShell prompt, issue the following commands:
. C:\users\administrator\desktop\key.ps1
Get-WindowsKey
There is a space character between the ‘.’ and the ‘C’ in the first line. And you do not need the quotation marks around administrator, although I don’t think that was the issue.
. : | : . : | : . tim
-
Proposed as answer by
Leo Han
Thursday, March 9, 2017 11:07 AM
-
Proposed as answer by
-
Hi Tim,
Problem here is that he separate command in 2 parts insted one line command. I am sorry if it was not clear but I thought that he will know that this is one line command. It is working 100 %. I attach image from my computer to prove it. It depends where
you save the file. I will save it in C:\ this time to be more easyHere is the powershell input from my computer
-
Edited by
Nedim Mehic
Wednesday, February 15, 2017 7:42 PM
-
Edited by
-
Yes, I understood it was a one-liner. But given it appeared that he was a novice when it came to PowerShell so I simply made it a little more straightforward for a novice.
. : | : . : | : . tim
-
Hi,
Are there any updates?
You could mark the reply as answer if it is helpful.
Best Regards,
Leo
Please remember to mark the replies as answers if they help.
If you have feedback for TechNet Subscriber Support, contact
tnmff@microsoft.com. -
i had used this script to get my product key but when i reuse to activate my new OS it fails; could you please advise what could be an issue.
-
You need to call Microsoft to see why your key is no longer working. Some keys have a limited number of activations. Maybe you have reached the limit. Microsoft will be able to tell you.
tim
-
Thanks Dave, It worked on Windows 2012 R2 Datacenter.
OSubhash
-
Thanks Dave, It worked on Windows 2012 R2 Datacenter.
OSubhash
Good news, please vote up my post.
Regards, Dave Patrick ….
Microsoft Certified Professional
Microsoft MVP [Windows Server] Datacenter ManagementDisclaimer: This posting is provided «AS IS» with no warranties or guarantees, and confers no rights.
-
When i run the command i get the appropriate response but the product key is still masked.
I am pulling this off of a 2012 R2 server to use on the Virtual server it is hosting.
-
above cmd completed with no error but i did not get the key
Finding your Windows server product key can be a daunting task for most users. Since the product key is embedded in the activation wizard of the software, it becomes difficult to retrieve the product key. However, various ways can help you find your Windows server product key. From third-party software to complex command lines, users get various methods to retrieve the product key. In this article, we will list six different methods that you can use without any external hassle. All the methods listed in the article will work on Windows servers, including Windows server 2022/2019/2016/2012, and more. Follow the article to the end for a detailed guide.
How Do I Find My Windows Server License Key
Workable Solutions | Step-by-step Troubleshooting |
---|---|
Check Server Product Key Box, Email |
If you have purchased a physical copy, the Windows server product key will be on a label…Full steps |
Check Microsoft Account | Log in to the Microsoft store using your official credentials…Full steps |
Use EaseUS Product Key Finder | Launch and run EaseUS Key Finder on the PC, and choose «Product Key» …Full steps |
Run CMD | Open the CMD and run it with administrator rights…Full steps |
Checking Windows Server Product Key Box, Email
One of the easiest methods to find the Windows server product key is searching the box windows came in. If you have purchased a physical copy, the Windows server product key will be on a label on the card inside the product box. This is one of the easiest methods that you can use to find your Windows server product key. However, if you have misplaced your product box, you can search your email for the official mail from Microsoft with Windows server product key details. If you have deleted the mail accidentally, you can check your junk mail folder or try other methods listed in the article below.
Check Microsoft Account or Contact Microsoft Support Team
You can find the Windows server product key from your official Microsoft account, no matter the Windows server. If you have purchased Windows from the Microsoft Store, the server product key will be stored digitally in your Microsoft account. To find the Windows server product key, follow the steps mentioned below:
- Log in to the Microsoft store using your official credentials.
- Under the downloads sections, navigate to the product key and click on Subscription.
- Under the Subscription menu, the server product key will be listed under the Digital Content section.
If you do not see your Windows server product key in your Microsoft account, it is advised that you must contact the Microsoft support team to assist you in finding the sever product key.
Click to Find Windows Server Product Key with EaseUS Product Key Finder
One of the easiest third-party software that allows you to find Windows server product keys is the EaseUS Key Finder. The software allows all Windows servers and Windows users to find product keys in simple clicks.
The EaseUS Key Finder’s interface is simple, and new users can follow the simple steps listed below to find the Windows server product key.
Step 1. Click «Windows» tab under the Registry Key.
Step 2. Check Windows product key on the right side. Click «Copy» to paste. Or select other two options:
«Save» — Save to local as a PDF file.
«Print» — Click to print key file.
Run CMD
If you want to find your Windows server product key, you can also use the command prompt. However, the command prompt will be only available for the OEM license. Before using the CMD method, it is advised that users must know the differences between different types of licenses. Once you are aware of the types of Windows licenses, follow the steps mentioned below.
- Open the CMD and run it with administrator rights.
- Once the tab is opening, copy and paste the command «wmic path softwarelicensingservice get OA3xOriginalProductKey».
- As soon as you enter the command mentioned above, the product key will appear.
Running CMD and typing complex commands can be difficult for most users. However, CMD shows the Windows server product key with specific commands.
Run Powershell Command
Similar to CMD, you can use the Powershell command to find the Windows server product key.
- Open Powershell and type the command listed below to find your server product key.
- powershell «(Get-WmiObject -query ‘select * from SoftwareLicensingService’).OA3xOriginalProductKey»
- Hit Enter, your Windows Server product key will show up in the PowerShell window.
Use Registry
The final method that you can use to find the Window server product key is the Registry editor. The free solution to finding the product key must be used with precaution to avoid further complications. To use Registry Editor, follow the steps mentioned below:
- Navigate to the Windows icon and right-click on the icon
- Select search option and type regedit
- Once you type, the Registry Editor will open
- Navigate to the path and find the product code value: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProtectionPlatform
- Double click on the BackupProductKeyDefault to find the server key.
The methods mentioned above to find the Windows server product key can be used for both older and newer versions of Windows. The use of methods will depend upon the user. If none of the methods works for you, it is advised that you must contact the Microsoft support team to find your product key.
Find Windows Server 2019/2016 or Older Server Product Keys
Now that you know the six different methods of finding server keys, you can use the methods to find Windows sever 2019/2016 or even older server product keys.
Windows Server Product Key Box: When you’ll purchase the Windows server 2019/2016, the server product key is listed in the product box and sent to your official mail.
Reaching Out To Microsoft Support Team: One of the easiest methods to find the Windows server 2019/2016 product key. You can also check your Microsoft account for the server product key.
Using EaseUS Product Key Finder: With the help of EaseUS Todo PC Trans Software, you can find your Windows server 2019/2016 product key with one click.
Run CMD: By typing the command mentioned above in CMD, you can easily find your Windows server product key.
Using Powershell: Similar to CMD, you just have to copy the command and paste it in the Powershell window to find your Windows server 2019/2016 product key
Using Registry: You can also use the registry editor to find the Windows server 2019/2016 product key without any hassle.
Conclusion
If you want to find your Windows server product key without investing additional effort and time, you must check your product box or official mail to get the server product key shared by Microsoft.
However, if you cannot locate your server product key on a Microsoft account or mail, you can rely on EaseUS Key Finder. The third-party software is the easiest and straightforward way to find the server product key. While command-line and Powershell require complex commands, you can use the EaseUS Key Finder and find the Windows server product key in one click. However, if you are well-versed with the commands, you can also use Registry Editor and Powershell to find the Windows server product key.
Как узнать ключ продукта установленной операционной системы Windows? Конечно проще всего воспользоваться специализированными программами (ProduKey, ShowKeyPlus и т.п.), но мы не ищем легких путей 🙂 В поисках ключа нам поможет PowerShell.
Ключ продукта Windows хранится в системном реестре, в разделе HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion, в параметре DigitalProductID.
Примечание. На самом деле у Windows есть два ключа продукта. Кроме ключа активации есть еще ключ установки (generic), находящийся в разделе HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DefaultProductKey. С этим ключом можно установить систему, но нельзя ее активировать.
Но просто так ключ посмотреть не удастся. Данные в DigitalProductID хранятся в двоичном виде, сам ключ занимает байты с 52 по 66. Кроме того данные зашифрованы в кодировке base 24.
Для того, чтобы узнать ключ, надо извлечь его из реестра и расшифровать. Для расшифровки используем следующий PowerShell скрипт. Сознаюсь, скрипт не мой 🙂 Я нашел его на просторах интернета и немного подправил, а также добавил комментарии. Кстати, в скрипте активно используются побитовые операторы.
# 24 символа, использующиеся в ключах продукта Microsoft
$base24 = ‘BCDFGHJKMPQRTVWXY2346789’;
# длина ключа продукта в символах
$decodeStringLength = 24;
# длина ключа продукта в байтах
$decodeLength = 14;
# строка с расшифрованным ключом
$decodedKey = ″ ″;
#Извлекаем зашифрованный ключ из реестра и сохраняем его в массив
$digitalProductId = (Get-Item ‘HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion’).GetValue(‘DigitalProductId’)[52..66]
#Проверяем наличие в ключе буквы ‘N’ (для Windows 8 и старше)
#Если третий бит младшего байта массива равен 1, то в номере присутствует буква ‘N’
$containsN = ($digitalProductId[$decodeLength] -shr 3) -bAnd 1;
#Для корректной расшифровки номера этот бит необходимо сбросить
$digitalProductId[$decodeLength] = $digitalProductId[$decodeLength] -band 0xF7;
<# Расшифровка ключа. Заключается в том, что полученное из реестра значение $digitalProductId переводится в систему счисления с основанием 24, затем каждая цифра заменяется на символ из $base24, индексом которого является эта цифра #>
for ($i = $decodeStringLength; $i -ge 0; $i−−) {
# Переменная для хранения индекса текущего символа, перед началом вычисления обнуляем
$digitMapIndex = 0;
for ($j = $decodeLength; $j -ge 0; $j−−) {
<# Размерность в байтах, поэтому исходное основание 256. Умножаем на него остаток от предыдущей итерации и добавляем цифру из следующего разряда #>
$digitMapIndex = ($digitMapIndex -shl -bXor $digitalProductId[$j];
<# Делим $digitMapIndex на количество символов в $base24. Частное попадает в $digitalProductId[$j],
а остаток от деления в $digitMapIndex #>
$digitalProductId[$j] = [System.Math]::DivRem($digitMapIndex, $base24.Length, [ref]$digitMapIndex);
}
# Находим в $base24 символ с полученным индексом и добавляем его в $decodedKey
$decodedKey = $decodedKey.Insert(0, $base24[$digitMapIndex]);
}
<# Если в ключе присутвует символ ′N′, то добавляем его. Для этого находим в расшифрованной строке первый символ и запоминаем его индекс в $base24. Затем удаляем первый символ, а в оставшуюся строку вставляем ′N′ в позицию с номером индекса удалённого символа #>
if ($containsN -eq 1) {
$index = $base24.IndexOf($decodedKey[0]);
$decodedKey = $decodedKey.Substring(1).Insert($index, ‘N’);
}
# Вставляем тире через каждые пять символов
for ($n = 20; $n -ge 5; $n -= 5){$decodedKey = $decodedKey.Insert($n, ‘-‘)}
# Формируем вывод, добавляем в него дополнительную информацию об операционной системе
$Target = [System.Net.Dns]::GetHostName();
$win32os = Get-WmiObject -Class ‘Win32_OperatingSystem’ -ComputerName $target;
$product = New-Object -TypeName System.Object;
$product | Add-Member -MemberType ‘NoteProperty’ -Name ‘Computer’ -Value $target;
$product | Add-Member -MemberType ‘NoteProperty’ -Name ‘Caption’ -Value $win32os.Caption;
$product | Add-Member -MemberType ‘NoteProperty’ -Name ‘OSArch’ -Value $win32os.OSArchitecture;
$product | Add-Member -MemberType ‘NoteProperty’ -Name ‘BuildNumber’ -Value $win32os.BuildNumber;
$product | Add-Member -MemberType ‘NoteProperty’ -Name ‘ProductID’ -Value $win32os.SerialNumber;
$product | Add-Member -MemberType ‘NoteProperty’ -Name ‘ProductKey’ -Value $decodedKey;
Write-Output $product;
Сохраняем код в файлик с расширением .ps1, запускаем и получаем результат. Готовый скрипт getproductkey.ps1.
Ну и чтобы убедиться в том, что скрипт работает правильно, проверим полученный результат с помощью программы ProduKey. Как видите, она выдает такой же ключ.
И еще. Если система была активирована корпоративным ключом (MAK) либо с помощью цифровой лицензии, то ключ не сохраняется в системе. В этом случае и скрипт выдаст что то вроде этого BBBBB-BBBBB-BBBBB-BBBBB-BBBBB.