Get windows version wmi

Самый простой способ быстро узнать версию и билд операционной системы Windows, установленной на компьютере – нажать сочетание клавиш
Win+R
и выполнить команду
winver
.

На скриншоте видно, что на компьютере установлена Windows 10 версия 22H2 (билд 19045.3324). Как номер релиза, так и номер сборки (билда) Windows позволяет однозначно идентифицироваться версию операционной системы на компьютере.

winver - окно с версией и биодом Windows

Также можно открыть окно с информацией о системе с помощью сочетания клавиш
Win+Pause
. Это откроет соответствующий раздел Settings (System -> About) или окно свойств системы (в зависимости от версии Windows).

Информация о версии Windows в панели Settings - data-lazy-src=

Начиная с Windows 10 20H2, классическое окно свойств системы в Control Panel скрыто и не доступно для прямого запуска. Чтобы вызвать его, выполните команду
shell:::{bb06c0e4-d293-4f75-8a90-cb05b6477eee}
.

Можно получить информацию о билде и версии Windows, установленной на компьютере, из командной строки.

Выполните команду:

systeminfo

Можно отфильтровать вывод утилиты:

systeminfo | findstr /B /C:"OS Name" /B /C:"OS Version"

Или воспользуйтесь WMI командой:

wmic os get Caption, Version, BuildNumber, OSArchitecture

команда systeminfo - вывести версию windows

Аналогом команды systeminfo в PowerShell является командлет Get-ComputerInfo:

Get-ComputerInfo | select OsName, OsVersion, WindowsVersion, OsBuildNumber, OsArchitecture

Get-ComputerInfo

Главный недостаток командлета Get-ComputerInfo – он выполняется довольно долго. Если вам нужно быстро узнать версию и билд Windows из скрипта PowerShell, лучше воспользоваться одной из следующий конструкций.

Версия Windows в переменной окружения:

[System.Environment]::OSVersion.Version

Из WMI класса:

Get-WmiObject -Class Win32_OperatingSystem | fl -Property Caption, Version, BuildNumber

В современных версиях PowerShell Core 7.x вместо командлета Get-WmiObject нужно использовать Get-CimInstance:

Get-CimInstance Win32_OperatingSystem | fl -Property Caption, Version, BuildNumber, OSArchitecture

Get-CimInstance Win32_OperatingSystem - узнать номер билда windows

Значение параметра OSArchitecture позволяет определить установлена ли на компьютере
x86
или
x64
версия Windows.

Можно получить номер билда и версии непосредственно из реестра Windows.

Reg Query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ProductName
Reg Query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v DisplayVersion
Reg Query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v CurrentBuild

или

Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"| select ProductName, DisplayVersion, CurrentBuild

версия и билд Windows в реестре

С помощью параметров реестра
ProductVersion
,
TargetReleaseVersion
и
TargetReleaseVersionInfo
в ветке HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate вы можете указать версию Windows, до которой ваш компьютер может автоматически обновиться. Эти параметры позволяют также запретить автоматическое обновление ОС до Windows 11.

Вы можете получить информацию о версии Windows на удаленном компьютере через PowerShell Remoting:

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

Или WMI/CIM:

Get-ciminstance Win32_OperatingSystem -ComputerName wksPC01 | Select PSComputerName, Caption, OSArchitecture, Version, BuildNumber | FL

Если компьютер добавлен в домен Active Directory, вы можете получить информацию о версии/билде Windows на компьютере из атрибутов компьютера в AD (как получить список версий и билдов Windows в домене Active Directory).

When troubleshooting a Windows computer, you may want to find out the operating system version. But what if you don’t have access to the GUI? Perhaps you need to get the same information from a remote computer? That’s where the awe of PowerShell shines through.

How do we get the Windows version the PowerShell way? Let’s explore several ways.

Method 1: PowerShell Get OS Version from the Registry

Would you be surprised that the Windows operating system information can be found inside the registry? Probably not. You can find that information in this location in the registry.

HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion

powershell check windows version

Viewing the Windows OS version in the registry editor is fine, but that’s not what we’re learning here. So, how do we perform the PowerShell get OS version from the registry method?

Open PowerShell and run this Get-ItemProperty command.

Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"

get os version powershell

But as you can see above, the command returns many properties we don’t need. So let’s clean it up by selecting only the properties we want.

Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" | ` 
Format-List ProductName,DisplayVersion,CurrentBuildNumber

Isn’t this a lot better?

check windows version powershell

Method 2: Query the Win32_OperatingSystem Class (WMI)

Through WMI classes, you can query different information about the local or remote computer. One of the details you can pull from WMI is the computer’s operating system version through the Win32_OperatingSystem or CIM_OperatingSystem class.

You can query WMI classes using the Get-WmiObject or Get-CimInstance cmdlets. There are differences between these two cmdlets that are not relevant to this task, but both will achieve the same goal.

Note. Get-CimInstance is the recommended and modern cmdlet.

# Windows PowerShell 
Get-WmiObject Win32_OperatingSystem | ` 
Format-List Caption, Version, BuildNumber

get operating system powershell

# PowerShell Core 
Get-CimInstance CIM_OperatingSystem | ` 
Format-List Caption, Version, BuildNumber

powershell osversion

If you want to query a remote computer instead, you must append the -ComputerName parameter followed by the remote computer name.

# Windows PowerShell 
Get-WmiObject Win32_OperatingSystem -ComputerName <COMPUTER_NAME> | ` 
Format-List Caption, Version, BuildNumber 

# PowerShell Core 
Get-CimInstance CIM_OperatingSystem -ComputerName <COMPUTER_NAME> | ` 
Format-List Caption, Version, BuildNumber

get windows version using powershell

Method 3: PowerShell Show Version from the System.Environment Class (.NET)

PowerShell can expose .NET classes and call their static methods. For example, the System.Environment class has an OSVersion property that returns the current operating system version.

Run the below command in PowerShell to get the Version property.

[System.Environment]::OSVersion.Version

Unfortunately, this method only shows the platform version and build numbers. The result does not say the friendly name (ie. Windows 11, Windows 10, etc.). Like in this example, the build number 19044 translates to Windows 10 20H2.

Refer to the List of Microsoft Windows versions.

powershell get operating system version

This method may not be the best option if you care to retrieve the operating system name instead of only the version numbers.

Method 4: PowerShell Check Windows Version with the Get-ComputerInfo Cmdlet

The Get-ComputerInfo cmdlet is a built-in cmdlet that returns various details about the local computer. If you run it on its own, you’ll get a result similar to the one below.

get operating system version powershell

But since we’re only interested in getting the Windows OS version, let’s append the -Property parameter with the specific properties we need.

Get-ComputerInfo -Property OSName,OSVersion

And that’s how you get the OS version the PowerShell way.

check windows version through powershell

Method 5: PowerShell Check Windows Version with SystemInfo Command

Like the Get-ComputerInfo cmdlet, the systeminfo.exe command is a native command that returns the computer information, too.

powershell get os version windows

But since systeminfo.exe is not a PowerShell cmdlet, it doesn’t produce the result as an object, so we can’t select specific properties from it. Instead, we can pass the result to the Select-String cmdlet to filter the OS Name and OS Version lines.

systeminfo.exe | Select-String "\bOS Name","\bOS Version"

Note. The \b switch is a regular expression to set a word boundary for the match. Without it, the result would also match BIOS because it has the OS characters.

get operating system with powershell

Cyril Kardashevsky

I enjoy technology and developing websites. Since 2012 I’m running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.

For troubleshooting purposes, or before deploying any software, it is good to know what is the Windows Operating system version that is currently running. We can easily find the OS details from My Computer properties, but if you want to get details from your customer’s machine to troubleshoot any issue, PowerShell is the best option to get all the required machine details.

In PowerShell, we can find operating system details in different ways, but to be safe we can use the WMI-based cmdlet Get-WmiObject, this command is compatible with Windows PowerShell 2.0. Using this command we can query the WMI class Win32_OperatingSystem to get the OS version number:

(Get-WmiObject Win32_OperatingSystem).Version

The above command only returns the os version number. Run the following command to get the display name of your Windows version.

(Get-WmiObject Win32_OperatingSystem).Caption
Output :
Microsoft Windows 7 Ultimate

We can use the select command to get the output of all the required OS-related properties.

Get-WmiObject Win32_OperatingSystem |
Select PSComputerName, Caption, OSArchitecture, Version, BuildNumber | FL

We can use the Get-WmiObject cmdlet in short form gwmi.

(gwmi win32_operatingsystem).caption

Get OS version of a remote computer

We can easily get the OS version details of a remote computer by adding the parameter -ComputerName to Get-WmiObject.

Get-WmiObject Win32_OperatingSystem -ComputerName "Remote_Machine_Name" |
Select PSComputerName, Caption, OSArchitecture, Version, BuildNumber | FL

Connecting a remote server/machine may require providing admin user credentials. In this case, you may receive the error message “Get-WmiObject : Access is denied“. Use the below command to pass user credentials to the Get-WmiObject command.

$PSCredential = Get-Credential "ComputerName\UserName"
#$PSCredential = Get-Credential "DomainName\UserName"

Get-WmiObject Win32_OperatingSystem -ComputerName "Remote_Machine_Name" -Credential $PSCredential |
Select PSComputerName, Caption, OSArchitecture, Version, BuildNumber | FL

Get OS details for a list of remote computers using PowerShell

You can use the following PowerShell script to find OS version details for multiple remote computers. First, create a text file named as “computers.txt” which includes one computer name in each line. You will get the output of the machine name, OS name, and version number in the CSV file OS_Details.csv.

Get-Content "C:\Temp\computers.txt"  | ForEach-Object{
$os_name=$null
$os_version=$null
$errorMsg=''
Try
{
$os_name = (Get-WmiObject Win32_OperatingSystem -ComputerName $_ ).Caption
}
catch
{
$errorMsg=$_.Exception.Message
}
if(!$os_name){
$os_name = "The machine is unavailable $errorMsg"
$os_version = "The machine is unavailable"
}
else{
$os_version = (Get-WmiObject Win32_OperatingSystem -ComputerName $_ ).Version 
}
New-Object -TypeName PSObject -Property @{
ComputerName = $_
OSName = $os_name
OSVersion = $os_version 
}} | Select ComputerName,OSName,OSVersion |
Export-Csv "C:\Temp\OS_Details.csv" -NoTypeInformation -Encoding UTF8

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
  • Средства администрирования windows это
  • Как писать батники для windows 10
  • Redis download for windows
  • Зеленые обои для windows 10