Как узнать версию windows через powershell

Время на прочтение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.

В статье рассмотрим несколько способов инвентаризации версии и билдов Windows (особенно актуально это для Windows 10) в домене Active Directory. Если у вас средств автоматизации сбора конфигураций компьютеров, например SCCM, GLPI c FusionInventory, или хотя бы сервер обновлений WSUS (он также позволяет показать версию Windows на обнаруженных компьютерах), вы можете использовать PowerShell скрипт для получения билдов Windows на компьютерах.

На отдельно-стоящем компьютере Windows можно получить номер билда из реестра или из SystemInfo:

Get-ItemProperty 'HKLM:SOFTWARE\Microsoft\Windows NT\CurrentVersion' | Select-Object ProductName, ReleaseID, CurrentBuild

Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer

Для получения списка активных компьютеров в домене Active Directory и версий (билдов) Windows на них можно использовать командлет Get-ADComputers.

Убедитесь, что на вашем компьютере установлен модуль Active Directory PowerShell и выполните команду:

Get-ADComputer -Filter {(Enabled -eq $True)} -Property * | Select-Object Name,OperatingSystem,OperatingSystemVersion

Get-ADComputer - вывести версии компьютеров и серверов Windows в Active Directory

Чтобы преобразовать номер билда Windows 10 и 11 в более привычный формат (21H1, 21H2 и т.д.), нужно использовать дополнительную функцию.

function ConvertWindowsBuild{
[CmdletBinding()]
param(
[string] $OperatingSystem,

[string] $OperatingSystemVersion
)
if (($OperatingSystem -like '*Windows 10*') –or ($OperatingSystem -like 'Windows 11*')) {
$WinBuilds= @{
'10.0 (22000)' = "Windows 11 21H2"
'10.0 (19044)' = "Windows 10 21H2"
'10.0 (19043)' = "Windows 10 21H1"
'10.0 (19042)' = "Windows 10 20H2"
'10.0 (18362)' = "Windows 10 1903"
'10.0 (17763)' = "Windows 10 1809"
'10.0 (17134)' = "Windows 10 1803"
'10.0 (16299)' = "Windows 10 1709"
'10.0 (15063)' = "Windows 10 1703"
'10.0 (14393)' = "Windows 10 1607"
'10.0 (10586)' = "Windows 10 1511"
'10.0 (10240)' = "Windows 10 1507"
'10.0 (18898)' = 'Windows 10 Insider Preview'
}
$WinBuild= $WinBuilds[$OperatingSystemVersion]
}
else {$WinBuild = $OperatingSystem}
if ($WinBuild) {
$WinBuild
} else {
'Unknown'
}
}

Теперь, чтобы получить список версий Windows с названиями билдов, IP адресами, и датой последнего входа (регистрации) компьютера в домене, выполните следующий PowerShell скрипт:

$Comps= Get-ADComputer -Filter {(Enabled -eq $True)} -properties *
$CompList = foreach ($Comp in $Comps) {
[PSCustomObject] @{
Name = $Comp.Name
IPv4Address = $Comp.IPv4Address
OperatingSystem = $Comp.OperatingSystem
Build = ConvertWindowsBuild -OperatingSystem $Comp.OperatingSystem -OperatingSystemVersion $Comp.OperatingSystemVersion
LastLogonDate = $Comp.LastLogonDate
}
}
$CompList | Out-GridView

Результат предоставлен в виде таблицы Out-Gridview либо экспортировать в CSV (
Export-Csv -Path .\win_builds_report.csv -NoTypeInformation
).

получить версию билда Windows на компьютерах в домене AD через powershell

Чтобы вывести суммарную статистику по количеству компьютеров с разными версиями Windows в домене:

$CompList | Group-Object -Property Build | Format-Table -Property Name, Count

Также можно удаленно опрашивать компьютеры и получить версию Windows на них через PowerShell Remoting. Этот метод намного более медленный, но позволить получить версию Windows на компьютерах, которые находятся в рабочей группе (как через PSRemoting удаленно подключиться к компьютеру в рабочей группе). Для получения информации с удаленных компьютеров можно использовать командлет Invoke-Command:

Invoke-Command -ScriptBlock {Get-ItemProperty 'HKLM:SOFTWARE\Microsoft\Windows NT\CurrentVersion' | Select-Object ProductName, ReleaseID, CurrentBuild} -ComputerName wsk-w10BO1| Select-Object PSComputerName,ProductName, ReleaseID, CurrentBuild

Можно получить версию Windows на нескольких компьютеров по списку из txt файла:

Invoke-Command –ComputerName (Get-Content c:\ps\comps.txt) -ScriptBlock {Get-ItemProperty 'HKLM:SOFTWARE\Microsoft\Windows NT\CurrentVersion' | Select-Object ProductName, ReleaseID, CurrentBuild}|Select-Object PSComputerName,ProductName, ReleaseID, CurrentBuild

С помощью рассмотренных PowerShell скриптов вы сможете определить версии и билды Windows на компьютерах домена, найти компьютеры с устаревшими билдами Windows 10 и обновить их (пример обновления билда Windows 10 из командной строки).

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

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?

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

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

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

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.

Get the Windows Version Using PowerShell

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:

Get Windows Version and Build Using PowerShell

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;

PowerShell get windows version

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.

  1. Using the [System.Environment] Class in PowerShell to Get the Windows Version

  2. Using the Get-ComputerInfo Cmdlet in PowerShell to Get the Windows Version

  3. Using the WMI Class With Get-WMIObject Cmdlet in PowerShell to Get the Windows Version

  4. Using the systeminfo Legacy Command PowerShell to Get the Windows Version

  5. Using the Get-CimInstance Legacy Command PowerShell to Get the Windows Version

  6. Conclusion

How to Get the Windows Version in PowerShell

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:

find windows version in powershell - output 2

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:

find windows version in powershell - output 3

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:

find windows version in powershell - output 4

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:

find windows version in powershell - output 5

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

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как посмотреть версию windows 10 на флешке
  • Linux монтирование сетевой папки windows в linux
  • Как вкл экранную клавиатуру на windows 10
  • Изменить расположение папок пользователя windows 10
  • Windows 10 for android limbo