Время на прочтение5 мин
Количество просмотров28K
Как же определить версию Windows, работающую в корпоративном окружении?
Вопрос кажется простым, правда?
Microsoft позволяет определить номер версии Windows различными способами:
- Существуют значения в реестре, которым отчаянно не хватает документации.
- Есть множество командлетов PowerShell, вызовов Windows API и т. п.
- Также есть варианты для конечного пользователя, например, команда
winver
, которая вызывает всплывающее окно с версией Windows. - И много других способов…
Разобраться во всём этом вам поможет наш пост.
Существует множество инструментов, позволяющих определить, какая версия Windows запущена у ваших клиентов, например, SCCM и PDQ. В этом посте мы рассмотрим встроенные способы определения версии Windows.
▍ Реестр
Для определения запущенной в системе версии Windows можно использовать следующие значения реестра:
Примечание: перечисленные в таблице значения официально не задокументированы Microsoft (см. ниже).
Предупреждение
Microsoft не сообщала об изменениях в этих значениях реестра, не документировала их официальную поддержку и не гарантировала, что в будущем не появится критических изменений. Из-за этого описанными выше ключами реестра пользоваться бывает иногда неудобно, учитывая непостоянство изменений этих ключей, вносимых Microsoft в прошлом. Примеры:
- ReleaseID не рекомендуется к использованию, начиная с версии 21H1. ReleaseID для 21H1 остаётся равным 2009.
- Server 2012R2 не имеет ReleaseID и DisplayVersion (они пока не были добавлены в Windows)
- Server 2016 имеет ReleaseID (1607), но не имеет DisplayVersion
- Server 2019 имеет ReleaseID (1809), но не имеет DisplayVersion
▍ PowerShell
Ниже приведено несколько примеров того, как можно использовать PowerShell, чтобы определить версию Windows, которая работает в системе:
# При помощи класса System.Environment
[System.Environment]::OSVersion
# При помощи класса CIM Win32_OperatingSystem
Get-CimInstance Win32_OperatingSystem
# При помощи исполняемого файла systeminfo
systeminfo.exe /fo csv | ConvertFrom-Csv
# При помощи командлета Get-ComputerInfo
# ПРИМЕЧАНИЕ: начиная с 21H1 OsHardwareAbstractionLayer не рекомендуется к использованию
Get-ComputerInfo | Select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
▍ Windows API Call
Единственный поддерживаемый (задокументированный) систематический способ определения версии Windows — при помощи вызова Windows API класса AnalyticsInfo. Это можно сделать через PowerShell:
<#
Класс AnalyticsInfo - задокументированный способ отслеживания версии ОС. Он возвращает
строковое значение. Формат этой строки не задокументирован, и нельзя полагаться
на определённое значение. Эти значения можно использовать только чтобы отличать
одну версию ОС от другой.
https://docs.microsoft.com/uwp/api
/windows.system.profile.analyticsversioninfo.devicefamilyversion
Этот API недоступен на Server Core
#>
$AnalyticsInfo = [Windows.System.Profile.AnalyticsInfo,Windows.System.Profile,ContentType=WindowsRuntime]
$VersionInfo = $AnalyticsInfo.GetMember( 'get_VersionInfo' )
$AnalyticsVersionInfo = $VersionInfo.Invoke( $Null, $Null )
# На моей тестовой машине этот код возвращает `2814751015109593`
$AnalyticsVersionInfo.DeviceFamilyVersion
<#
Строго говоря, строку *можно* парсить, если вам любопытно, что в ней,
хотя этого делать *нельзя*
https://stackoverflow.com/questions/31783604/windows-10-get-devicefamilyversion
#>
$v = [System.Int64]::Parse( $AnalyticsVersionInfo.DeviceFamilyVersion )
$v1 = ( $v -band 0xFFFF000000000000l ) -shr 48
$v2 = ( $v -band 0x0000FFFF00000000l ) -shr 32
$v3 = ( $v -band 0x00000000FFFF0000l ) -shr 16
$v4 = $v -band 0x000000000000FFFFl
# На моей тестовой машине этот код возвращает `10.0.19043.985`
[System.Version]::Parse( "$v1.$v2.$v3.$v4" )
<#
Не опубликовано *никакого* способа декодирования, позволяющего преобразовать
какое-то из приведённых выше значений в удобную для отображения версию,
например `21H1`
Показанная ниже альтернатива доступна только в последних версиях ОС,
начиная с Azure Stack HCI, версии 20H2
#>
Get-ComputerInfo -Property 'osDisplayVersion'
▍ Варианты для конечного пользователя
В документации Microsoft перечислено несколько команд, которые конечные пользователи могут применять для определения запущенной версии Windows. Например, чтобы выяснить версию Windows, можно использовать команду winver
или меню Параметров Windows. Эти способы предназначаются больше для конечных пользователей, чем для масштабного определения версии системы. Ниже показаны примеры:
▍ Почему это важно
После определения запущенной в системе версии Windows можно использовать эту информацию выполнения детерминированных действий: обновлений Windows, установки патчей и т. п. Например:
Можно запросить значение реестра DisplayVersion
(см. раздел «Реестр» выше), чтобы определить запущенную версию Windows. Затем можно задать перечисленные ниже значения реестра, чтобы сообщить Windows, какая версия должна быть запущена в системе. При помощи трёх ключей реестра вы полностью контролируете то, до какой версии Windows ваши системы будут пытаться обновиться!
Эти значения реестра можно задавать или напрямую, или через групповую политику.
▍ Куда двигаться дальше
Хотя вам необязательно управлять версиями Windows, запущенными на компьютерах компании, ей было бы ценно знать, какие это версии Windows. По крайней мере, потому, что Microsoft регулярно прекращает поддержку разных версий Windows.
Стоит также заметить, что показанные выше примеры — это неполный список способов определения версии Windows, однако он полезен для людей, управляющих окружением Windows. Эти способы оказались полезными для меня при устранении проблем, задании политик и т. п. Надеюсь, вам они тоже пригодятся.
Кроме того, ситуация с управлением версиями Windows постоянно меняется, поэтому я напишу ещё один пост, когда Microsoft перестанет рекомендовать перечисленные здесь способы.
Дополнительные ссылки
- Microsoft nixes update deferral settings, but gives us a TargetReleaseVersionInfo
- Windows 10 Version History
- Windows Server Versions.
To check the Windows version using PowerShell, you can utilize the following command that retrieves and displays the version information of the operating system.
Get-ComputerInfo | Select-Object WindowsVersion, WindowsBuildLabEx
Understanding Windows Versioning
What is Windows Version?
Windows versioning refers to the unique identifiers assigned to different iterations of the Windows operating system. Each version comes with specific features, improvements, and updates, which can significantly impact user experience, security, and software compatibility. For instance, major Windows versions include Windows 7, Windows 8, Windows 10, and Windows 11. Knowing your current version is essential for executing tasks effectively and ensuring compatibility with various applications and tools.
Why Check Windows Version?
There are several scenarios where checking the Windows version is crucial:
- Software Compatibility: Certain software applications require specific Windows versions or higher to function correctly.
- Automation Scripts: Many automation tasks or deployment scripts need to adapt based on the operating system version.
- Troubleshooting: When faced with issues, knowing the Windows version can help in identifying potential fixes or support forums tailored to that version.
Get ADFS Version PowerShell: A Quick Guide
Basic Command to Retrieve Windows Version
One of the simplest commands to check the Windows version in PowerShell is through the `Get-ComputerInfo` cmdlet. This command retrieves detailed system information, including the Windows version.
Here’s how you can do it:
Get-ComputerInfo | Select-Object WindowsVersion, WindowsBuildLabEx
Explanation:
- Get-ComputerInfo retrieves comprehensive details about the system.
- Select-Object allows you to pick specific properties to display; in this case, `WindowsVersion` and `WindowsBuildLabEx`, which provide both version and build information.
Using WMI for Windows Version
For those who may be using an older version of PowerShell, the `Get-WmiObject` cmdlet remains a robust solution.
Get-WmiObject Win32_OperatingSystem | Select-Object Version, BuildNumber
Note: While `Get-WmiObject` works well, it is considered somewhat legacy, and newer versions of PowerShell encourage the use of CIM cmdlets.
Using CIM Cmdlets
CIM (Common Information Model) cmdlets are the modern approach to retrieving system data. Here’s how you can use them to check your Windows version:
Get-CimInstance Win32_OperatingSystem | Select-Object Version, BuildNumber
Advantages of using CIM include better performance and compatibility with remote systems compared to WMI.
Which Version PowerShell Is Right for You?
Printing and Showing the Windows Version
PowerShell Print Windows Version
Sometimes, you may want to print the Windows version directly to the console. This can be useful for quick checks or when building scripts that report system status.
$windowsVersion = (Get-ComputerInfo).WindowsVersion
Write-Output "Your Windows Version is: $windowsVersion"
Explanation:
- Here, you assign the Windows version to a variable `$windowsVersion` and then use Write-Output to display it in a user-friendly manner.
PowerShell Show Windows Version in a User-Friendly Format
For better readability, displaying Windows version info in a structured table can enhance clarity.
$versionInfo = Get-ComputerInfo | Select-Object WindowsVersion, WindowsBuildLabEx
$versionInfo | Format-Table -AutoSize
Explanation:
- Format-Table is used here to create a cleanly formatted output that’s easy to read, especially when providing multiple entries or details.
Check Pending Reboot in PowerShell: A Quick Guide
Advanced Techniques
Filtering Specific Information
When dealing with large outputs, it can be beneficial to filter out only the information you need.
Get-ComputerInfo | Select-Object -Property WindowsVersion, WindowsArchitecture
Discussion:
This command will show you just the Windows version and the architecture (32-bit or 64-bit), which is often sufficient for various tasks.
Storing Windows Version in a Variable for Later Use
PowerShell allows you to store information in variables for later use, which can streamline your scripts and command executions.
$winVersion = Get-ComputerInfo | Select-Object -ExpandProperty WindowsVersion
# Use $winVersion in subsequent commands
Using the `-ExpandProperty` parameter allows you to extract the value directly rather than getting an object, making it more straightforward for subsequent operations.
Export Windows Version Information to a File
In many IT environments, recording system configurations is critical. You can export your version information to a CSV file for records or reporting purposes.
Get-ComputerInfo | Select-Object WindowsVersion, WindowsBuildLabEx | Export-Csv -Path "WindowsVersion.csv" -NoTypeInformation
Importance: Exporting this data can assist in audits, documentations, or when you need to relay information to support teams.
Invoke-PowerShell: Mastering Command Execution Effortlessly
Practical Applications
Automating Version Checks
PowerShell can also help automate tasks, such as notifying users when their version is outdated. Here’s a simple script to check versions:
$latestVersion = "10.0.19042" # Example latest version for reference
$currentVersion = Get-ComputerInfo | Select-Object -ExpandProperty WindowsVersion
if ($currentVersion -ne $latestVersion) {
Write-Output "Update Available: Current Version $currentVersion, Latest Version $latestVersion"
} else {
Write-Output "You are up to date!"
}
This simple check can save time and ensure that users are aware of the necessary updates.
Troubleshooting Common Issues
While checking the Windows version with PowerShell is generally straightforward, some common pitfalls may arise, such as:
- WMI service issues: Ensure the WMI service is running if your commands return errors.
- Access permissions: Running PowerShell as an administrator may be necessary to retrieve certain system information.
Consider revisiting the command syntax or the properties you are querying if you encounter issues.
Mastering Wget in Windows PowerShell for Easy Downloads
Conclusion
Being able to check Windows version using PowerShell is not just a useful skill; it’s a vital one for IT professionals and enthusiasts alike. By utilizing the commands and techniques discussed in this article, you can rapidly ascertain system specifications, automate version checks, and ensure your systems remain compliant and up-to-date.
Remember to practice these commands to make them a part of your daily toolkit, and explore additional resources to deepen your PowerShell expertise.
As a system administrator or developer, I often need to know the specific version of Windows running on a machine. In this tutorial, I will explain how to get the Windows version using PowerShell using different methods.
Now, let me show you different methods to get the Windows version using PowerShell.
Method 1: Using the [Environment]::OSVersion Property
One of the simplest ways to retrieve the Windows version using PowerShell is by accessing the [Environment]::OSVersion
property. Here’s an example:
$windowsVersion = [Environment]::OSVersion
Write-Host "Windows Version: $($windowsVersion.Version)"
In this code snippet, we assign the [Environment]::OSVersion
property to the $windowsVersion
variable. We then use Write-Host
to display the version information by accessing the Version
property of $windowsVersion
.
I executed the above PowerShell script and you can see it displays me the current Windows version that I am using.
For instance, let’s say you’re a system administrator at a company in New York, and you need to check the Windows version of a server named “NYServer01”. You can use the following script:
$serverName = "NYServer01"
$windowsVersion = Invoke-Command -ComputerName $serverName -ScriptBlock { [Environment]::OSVersion }
Write-Host "Windows Version on $serverName : $($windowsVersion.Version)"
This script uses the Invoke-Command
cmdlet to execute the command remotely on the specified server and retrieve the Windows version information.
If you want to get Windows Version and Build using PowerShell, then you can use the [System.Environment]::OSVersion
property. This property provides the version number in a more granular format.
[System.Environment]::OSVersion.Version
This command will output something like:
Major Minor Build Revision
----- ----- ----- --------
10 0 22631 0
I executed the above PowerShell cmdlet, and you can see the exact output in the screenshot below:
Check out Get HP Laptop Model and Serial Number Using PowerShell
Method 2: Using the Registry
Another approach to get the Windows version is by querying the registry. PowerShell allows you to access registry values easily. Here’s an example:
$registryKey = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
$windowsVersion = (Get-ItemProperty -Path $registryKey -Name ReleaseID).ReleaseID
Write-Host "Windows Version: $windowsVersion"
In this code, we specify the registry key path that contains the Windows version information. We then use the Get-ItemProperty
cmdlet to retrieve the value of the ReleaseID
registry entry and store it in the $windowsVersion
variable.
For example, let’s say you’re an IT consultant based in California, and a client asks you to check the Windows version of their workstation named “LAWorkstation”. You can use the following script:
$computerName = "LAWorkstation"
$registryKey = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
$windowsVersion = Invoke-Command -ComputerName $computerName -ScriptBlock {
(Get-ItemProperty -Path $registryKey -Name ReleaseID).ReleaseID
}
Write-Host "Windows Version on $computerName : $windowsVersion"
This script uses Invoke-Command
to execute the registry query remotely on the specified workstation and retrieve the Windows version.
Check out How to Use PowerShell Read-Host?
Method 3: Using the Get-ComputerInfo Cmdlet
Starting from Windows PowerShell 5.1, you can use the Get-ComputerInfo
cmdlet to retrieve detailed information about a computer, including the Windows version. Here’s an example:
$computerInfo = Get-ComputerInfo
Write-Host "Windows Version: $($computerInfo.OsVersion)"
Write-Host "Windows Edition: $($computerInfo.OsName)"
In this code, we use the Get-ComputerInfo
cmdlet to retrieve computer information and store it in the $computerInfo
variable. We then access the OsVersion
and OsName
properties to display the Windows version and edition, respectively.
For instance, let’s say you’re a IT support specialist in Texas, and you need to check the Windows version and edition of a user’s laptop named “DallasLaptop”. You can use the following script:
$laptopName = "DallasLaptop"
$computerInfo = Invoke-Command -ComputerName $laptopName -ScriptBlock { Get-ComputerInfo }
Write-Host "Windows Version on $laptopName : $($computerInfo.OsVersion)"
Write-Host "Windows Edition on $laptopName : $($computerInfo.OsName)"
This script uses Invoke-Command
to execute Get-ComputerInfo
remotely on the specified laptop and retrieve the Windows version and edition information.
Check out How to Use PowerShell Get-Process?
Method 4: Using WMI (Windows Management Instrumentation)
WMI is a powerful tool for retrieving system information, including the Windows version. Here’s an example of how to use WMI with PowerShell:
$wmiQuery = "SELECT * FROM Win32_OperatingSystem"
$operatingSystem = Get-WmiObject -Query $wmiQuery
Write-Host "Windows Version: $($operatingSystem.Version)"
In this code, we define a WMI query to select all properties from the Win32_OperatingSystem
class. We then use the Get-WmiObject
cmdlet to execute the query and store the result in the $operatingSystem
variable. Finally, we access the Version
property to display the Windows version.
I executed the above PowerShell script; it displays me the exact information like in the screenshot below;
For example, let’s say you’re a system administrator in Florida, and you need to check the Windows version of a server named “MiamiServer”. You can use the following script:
$serverName = "MiamiServer"
$wmiQuery = "SELECT * FROM Win32_OperatingSystem"
$operatingSystem = Invoke-Command -ComputerName $serverName -ScriptBlock {
Get-WmiObject -Query $wmiQuery
}
Write-Host "Windows Version on $serverName : $($operatingSystem.Version)"
This script uses Invoke-Command
to execute the WMI query remotely on the specified server and retrieve the Windows version information.
Conclusion
In this tutorial, I explained various methods to retrieve the Windows version using PowerShell. You can use various methods such as using the [Environment]::OSVersion
property, querying the registry, utilizing the Get-ComputerInfo
cmdlet, or leveraging WMI, etc.
I am sure this tutorial will help you as a PowerShell administrator.
You may also like:
- PowerShell Compare-Object
- How to List Local Administrators Using PowerShell?
- How to Get Window Titles Using PowerShell?
- Rename a Computer Using PowerShell
- How to Retrieve Your Windows Product Key Using PowerShell?
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.
-
Home
-
Partition Magic
- How to Get Windows Version in PowerShell? | Here’re 5 Ways
By Ariel | Follow |
Last Updated
A lot of users don’t know how to make PowerShell get Windows version. Are you searching for the answer? This post on MiniTool is worth reading. It provides 5 simple ways to get Windows version PowerShell on Windows 10/11.
PowerShell is a practical Windows built-in command-line shell and scripting environment tool. It’s widely used by people to do various works such as PowerShell map network drive, PowerShell get current username, PowerShell change directory, PowerShell copy files, PowerShell gets folder size, PowerShell install SSH, etc.
However, a lot of users and even professionals don’t know how to do these works in PowerShell. So, you may find many answers that lack detailed steps and clear screenshots in different forums. Don’t worry. This post walks you through the full steps to get OS version PowerShell.
What Command Can Be Used to Check Windows Version PowerShell
What command can make PowerShell get OS version? After investigating extensive user comments and performing verifications, we find many cmdlets can find detailed information about Windows version PowerShell. Here we summarize them as follows:
- Systeminfo: It will display detailed information about a computer and its OS, including system version, Windows build, security information, etc.
- System.Environment: It can be used to check the current environment and Windows version of a computer.
- Get-ComputerInfo: It can specify the Windows version and operating system properties in PowerShell.
- Get-ItemProperty: It can get the properties of the Windows version in PowerShell.
- Get-CimInstance: It can get the specified information about the Windows build version in PowerShell.
How to Make PowerShell Get Windows Version on Windows 10/11
This part will show you how to let PowerShell get OS version using the following 5 methods. You can try them in order or choose one that works best for you.
Tips:
Some operations require your computer to have PowerShell v5.1 or a higher version installed. If you are not using the latest version, read this post “How to Update PowerShell Version to v7.2.5 for Windows 10/11”.
# 1. PowerShell Get Windows Version via Systeminfo
If you want to get Windows version PowerShell directly, you can use the Systeminfo command. Here’s how to use it.
Step 1. Press the Win + R keys to open the Run box, and then type powershell in it and press Ctrl + Shift + Enter keys to open the elevated PowerShell window.
Step 2. In the pop-up window, type the systeminfo command and hit Enter. Then you will get detailed information about your computer, including Windows OS version, OS name, system type, etc.
# 2. PowerShell Get Windows Version via System.Environment
The System.Environment class can also help you get PowerShell Windows version on Windows 10/11. To do this work, you just need to open the elevated PowerShell window as we explained above, type the following command and hit Enter to access the value of the Windows version.
[System.Environment]::OSVersion.Version
# 3. PowerShell Get Windows Version via Get-ComputerInfo
Another simple method to make PowerShell get operating system version is to use the Get-ComputerInfo command. It will display the Windows version, Windows Product name, and OS hardware information. You can type the following command in PowerShell and hit Enter to run it.
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
# 4. PowerShell Get Windows Version via Get-ItemProperty
The Get-ItemProperty cmdlet can help you check Windows version PowerShell using the Registry key. To run it, open the elevated PowerShell window, type the following command, and hit Enter. The output in the following picture indicates that the current Windows version is “2009”.
(Get-ItemProperty “HKLM:SOFTWAREMicrosoftWindows NTCurrentVersion”).ReleaseId
# 5. PowerShell Get Windows Version via Get-CimInstance
To get OS version PowerShell via the Get-CimInstance command, you can open the PowerShell window, type the following command and hit Enter to get the specified Windows OS version. For example, the current Windows version of my computer is Windows 10 build 19045.
(Get-CimInstance Win32_OperatingSystem).version
Further reading: If you enter some issues like file system corruption and low disk space on Windows, don’t worry. MiniTool Partition Wizard can help you fix them easily by checking file system errors, extending/resizing partitions, analyzing disk space, upgrading to a larger hard disk, etc.
MiniTool Partition Wizard FreeClick to Download100%Clean & Safe
About The Author
Position: Columnist
Ariel has been working as a highly professional computer-relevant technology editor at MiniTool for many years. She has a strong passion for researching all knowledge related to the computer’s disk, partition, and Windows OS. Up till now, she has finished thousands of articles covering a broad range of topics and helped lots of users fix various problems. She focuses on the fields of disk management, OS backup, and PDF editing and provides her readers with insightful and informative content.
-
Using the
[System.Environment]
Class in PowerShell to Get the Windows Version -
Using the
Get-ComputerInfo
Cmdlet in PowerShell to Get the Windows Version -
Using the WMI Class With
Get-WMIObject
Cmdlet in PowerShell to Get the Windows Version -
Using the
systeminfo
Legacy Command PowerShell to Get the Windows Version -
Using the
Get-CimInstance
Legacy Command PowerShell to Get the Windows Version -
Conclusion
The fastest way to get which Windows operating system your computer has is to use the winver
command. In Windows PowerShell, there are multiple ways to get your Windows version operating system, and we will discuss them here in this article.
Various methods exist to accomplish this, each with its advantages and use cases. In this article, we’ll explore five different approaches to get the Windows version in PowerShell.
Each method offers unique insights into the Windows environment, providing administrators and scripters with versatile tools to gather essential system information.
Using the [System.Environment]
Class in PowerShell to Get the Windows Version
In PowerShell, you can retrieve detailed information about the Windows version using the [Environment]::OSVersion.Version
method. This method accesses the static Version
property of the OSVersion
property in the Environment
class, providing a straightforward way to access the operating system version.
Example Code:
[System.Environment]::OSVersion.Version
When we use [Environment]::OSVersion.Version
, we’re accessing the OSVersion
property of the Environment
class, which provides information about the operating system environment. Specifically, we’re retrieving the Version
property of this object, which contains details about the Windows version.
This method returns a System.Version
object, which represents the version of the operating system as a combination of major and minor version numbers. By accessing the Major
and Minor
properties of this object, we can extract these version numbers and use them as needed in our PowerShell script.
Output:
We may refer to the official Microsoft Document to cross-reference the current Windows version operating system that you are currently running.
However, this will not show the correct version if you’re using the newest operating system, like Windows 11 or Windows Server 2019, as it will still show a Major build 10, which represents Windows 10 and Windows Server 2016. Therefore, the command above will only show proper values if you run Windows 10 and Windows Server 2016 below.
Using the Get-ComputerInfo
Cmdlet in PowerShell to Get the Windows Version
In PowerShell, you can easily retrieve detailed information about the Windows operating system using the Get-ComputerInfo
cmdlet. This cmdlet gathers information about the local computer system, including the operating system name, version, and hardware abstraction layer (HAL).
Example Code:
Get-ComputerInfo | Select-Object OSName, OSVersion, OsHardwareAbstractionLayer
When we use the Get-ComputerInfo
cmdlet followed by piping it to Select-Object
, we’re retrieving comprehensive information about the local computer system. By specifying the properties OSName
, OSVersion
, and OsHardwareAbstractionLayer
, we’re selecting specific details about the operating system, such as its name, version, and hardware abstraction layer (HAL).
This method allows us to gather detailed information about the Windows environment, which can be useful for various administrative tasks, troubleshooting, or scripting purposes. By accessing and displaying these properties, we gain insights into the configuration and specifications of the Windows system, aiding in system management and maintenance.
Output:
Using the WMI Class With Get-WMIObject
Cmdlet in PowerShell to Get the Windows Version
We may also use the Windows Management Instrumentation (WMI) class to check for the current version of your operating system.
Example Code:
(Get-WmiObject -class Win32_OperatingSystem).Caption
When we execute (Get-WmiObject -class Win32_OperatingSystem).Caption
, we’re utilizing the Get-WmiObject
cmdlet to query Windows Management Instrumentation (WMI) for information about the operating system. Specifically, we’re targeting the Win32_OperatingSystem
class, which holds details about the operating system.
By accessing the .Caption
property of the resulting object, we’re retrieving the name of the operating system. This method offers a straightforward approach to obtaining the Windows version information directly through PowerShell, making it convenient for various scripting and administrative tasks.
Output:
Unlike the [System.Environment]
class and Get-ComputerInfo
cmdlet, the WMI object correctly displays the Windows operating system version if you’re using the latest version.
Using the systeminfo
Legacy Command PowerShell to Get the Windows Version
We can also use the systeminfo
legacy command with Windows PowerShell cmdlet wrappers to output the detailed operating system version. By combining systeminfo
with PowerShell cmdlets, you can extract specific information about the Windows version.
systeminfo /fo csv | ConvertFrom-Csv | select OS*, System*, Hotfix* | Format-List
When we execute the command systeminfo /fo csv
, we’re utilizing the systeminfo
command-line tool to gather detailed system information in CSV format.
Then, we use ConvertFrom-Csv
to convert the CSV-formatted output into PowerShell objects. By piping the result into Select
, we filter the properties we’re interested in, specifically those starting with OS
, System
, and Hotfix
.
Finally, we apply Format-List
to present the information in a formatted list view.
Output:
Using the Get-CimInstance
Legacy Command PowerShell to Get the Windows Version
This cmdlet is part of the Common Information Model (CIM) infrastructure in PowerShell, allowing you to query system information in a standardized way. By targeting the Win32_OperatingSystem
class, you can access properties such as the operating system name and version.
(Get-CimInstance Win32_OperatingSystem) | Select-Object Caption, Version
When we execute (Get-CimInstance Win32_OperatingSystem) | Select-Object Caption, Version
, we’re utilizing the Get-CimInstance
cmdlet to retrieve information about the Windows operating system from the Win32_OperatingSystem
class. This class represents various properties of the operating system. By piping the result into Select-Object
, we specify the properties we’re interested in, which are Caption
(representing the name of the operating system) and Version
.
Output:
Conclusion
In PowerShell, obtaining the Windows version is essential for system administration and scripting tasks. We’ve explored five different methods to accomplish this: using the [System.Environment]
class, Get-ComputerInfo
cmdlet, Get-WmiObject
cmdlet, systeminfo
command, and Get-CimInstance
cmdlet.
Each approach offers distinct advantages and may be preferred depending on specific requirements and scenarios. Whether it’s accessing the version directly through the [System.Environment]
class or querying detailed system information using Get-ComputerInfo
or Get-CimInstance
, PowerShell provides robust tools for effectively managing and monitoring Windows environments.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe