Windows server version 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.

Finding the PowerShell version is important if you are a system administrator for a network consisting of Windows Servers, Windows based workstations or client computers. Finding the PowerShell version can help you to find which features or cmdlets are supported in the PowerShell version your computers are running.

Note that there are two different base PowerShell versions available. First version I want to mention here is «Windows PowerShell». «Windows PowerShell» is the version of PowerShell, which is shipped with Windows Server Operating Systems. The version of «Windows PowerShell» packed with Windows Server 2025 installation media is 5.1.

PowerShell 7.x is the platform independent version, supported on Windows, Linux and Mac Operating Systems. May be because of being actively developed for different Operating Systems, 7.x version is not included by default, with the Windows Server installation media. You may download and install PowerShell 7.x version from the Microsoft website. Please visit the following Microsoft webpage link to find more information about how to install the latest version of PowerShell.

If you have many Windows based computers/servers in your network environment, it is always better to find the version of the PowerShell running in each Windows computer, because if any feature in your PowerShell script is not supported by the PowerShell version in any machine, there is chance for your PowerShell script to fail in that computer.

Finding «Windows PowerShell» version using «$PSVersionTable»

Finding the PowerShell version using «$PSVersionTable» is useful in Windows Server Core installations, because there are no GUI tools in Server Core installations.

Step 01 – To find the PowerShell version of the «Windows PowerShell», open the Windows PowerShell terminal. You can open the «Windows PowerShell» terminal by typing «powershell.exe» at Windows search box and then by clicking the Windows PowerShell from the search results.

type-powershell.exe-windows-search.jpg

Step 02 – Type $PSVersionTable in Windows PowerShell and press «Enter» key to view the Windows PowerShell version. Please refer the below screenshot.

psversiontable-variable-to-find-psversion.jpg

As you can see from the above image, PSVersion (the first line in the $PSVersionTable) shows the version of the Windows PowerShell shipped with the current Windows Server installation media. In this case, the PSVersion is 5.1.26212.5000.

Finding «Windows PowerShell» version from the Windows Registry

Warning – Please be careful. If you do not know what is Windows Registry and how critical & important is the Windows Registry, do not try to open Windows Registry. A mistake while editing the Windows Registry can seriously damage your Windows Server installation or your whole network.

Finding PowerShell version using Windows Registry is useful in Windows Server with Desktop experience.

Step 01 – Type «regedit.exe» in your Windows Search box, and then click «regedit.exe» from the search results. Please refer below screenshot.

type-regedit.exe-windows-search.jpg

Step 02 – The Windows Registry editor application will be opened. In Windows Registry editor, expand Computer > HKEY_LOCAL_MACHINE > SOFTWARE > Microsoft, as shown in below screenshot.

psversion-windows-registry-01.jpg

Step 03 – Scroll down to PowerShell and then to PowerShellEngine. Inside PowerShellEngine, you can view the «PowerShellVersion» registry entry. You can view that in this case, the «PowerShellVersion» is 5.1.26212.5000.

psversion-windows-registry-02.jpg

Written by Jajish Thomas.

Last updated on 2nd June, 2024.

В этой статье мы рассмотрим какие версии PowerShell существуют, в чем отличие Windows PowerShell от PowerShell Core и как узнать, какая версия PowerShell установлена на локальном или удаленных компьютерах.

Содержание:

  • История версии PowerShell, PowerShell Core
  • Как узнать версию PowerShell из консоли?
  • Получаем версию PowerShell на удаленных компьютерах

История версии PowerShell, PowerShell Core

По умолчанию PowerShell устанвлен во всех версиях Windows, начиная с Windows 7 SP1 и Windows Server 2008 R2 SP1. В следующей таблице представлен список актуальных версий PowerShell:

Версия PS Примечание
PowerShell 1.0 Можно было установить вручную в Windows Server 2003 SP1 и Windows XP
PowerShell 2.0 Предустановлен в Windows Server 2008 R2 и Windows 7
PowerShell 3.0 Установлен в Windows 8 и Windows Server 2012
PowerShell 4.0 Предустановлен в Windows 8.1 и Windows Server 2012 R2
PowerShell 5.0 Предустановлен в Windows 10 RTM, и автоматически обновляется до 5.1 через Windows Update
PowerShell 5.1 Встроен в Windows 10 (начиная с билда 1709) и Windows Server 2016
PowerShell Core 6.0 и 6.1 Следующая кроссплатформенная версия PowerShell (основана на .NET Core), которую можно установить не только во всех поддерживаемых версиях Windows, но и в MacOS, CentOS, RHEL, Debian, Ubuntu, openSUSE
PowerShell Core 7.0 Самая последняя версия PowerShell, вышедшая в марте 2020 (в новом релизе выполнен переход с .NET Core 2.x на 3.1)

Вы можете вручную установить более новую версию PowerShell в предыдущих версиях Windows. Для этого нужно скачать и установить соответствующую версию Windows Management Framework (PowerShell входит в его состав).

Стоит обратить внимание, что последние 2 года Microsoft приостановила развитие классического Windows PowerShell (выпускаются только исправления ошибок и безопасности) и сфокусировалась на открытом кроссплатформенном PowerShell Core. В чем отличия Windows PowerShell от PowerShell Core?

  • Windows PowerShell основан на NET Framework (например, для PowerShell 5 требуется .NET Framework v4.5, нужно убедиться что он установлен). PowerShell Core основан на .Net Core;
  • Windows PowerShell работает только на ОС семейства Windows, а PowerShell Core является кроссплатформенным и будет работать в Linux;
  • В PowerShell Core нет полной совместимости с Windows PowerShell, однако Microsoft работает на улучшением обратной совместимости со старыми командлетами и скриптами (перед переходом на PowerShell Core рекомендуется протестировать работу старых PS скриптов). В PowerShell 7 обеспечивается максимальная совместимсть с Windows PowerShell.
  • Редактор PowerShell ISE нельзя использовать для отладки скриптов PowerShell Core (но можно использовать Visual Studio Code)
  • Т.к. Windows PowerShell более не развивается, рекомендуется постепенно мигрировать на PowerShell Core.

Как узнать версию PowerShell из консоли?

Самый простой способ определить какая версия PowerShell у вас установлена с помощью команды:

host

Следующий скриншот из Windows 10, в которой как и в Windows Server 2016 по умолчанию установлен PowerShell 5.1.

как определить установленную версию powershell из консоли

или

$PSVersionTable

Можно получить только значении версии:

$PSVersionTable.PSVersion.major

(в этом примере мы получили версию PSVersion 2.0 с чистого Windows Server 2008 R2)

Команда
$PSVersionTable
корректно работает в PowerShell Core на различных операционных системах.

Также можно узнать установленную версию PowerShell через реестр. Для этого нужно получить значение параметра PowerShellVersion из ветки реестра HKLM\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine с помощью Get-ItemProperty

(Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion

узнать версию powershell xthtp httcnhf

Данный способ работает, начиная с Windows Server 2012/Windows 8. В Windows Server 2008 R2/ Windows 7 нужно получить значение параметра реестра в другой ветке:

(Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion

версия powershell в windows server 2008r2

Для определения установленной версии PowerShell Core нужно использовать команду:

(Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PowerShellCore\InstalledVersions* -Name 'SemanticVersion').SemanticVersion

Получаем версию PowerShell на удаленных компьютерах

Для получения версии PowerShell на удаленных компьютерах нужно использовать значение переменной окружения $PSVersionTable или получать данные непосредственно из реестра. Другие способы могут возвращать некорректные данные.

Вы можете получить версию PowerShell с удаленного компьютера с помощью команды Invoke-Command:

Invoke-Command -ComputerName dc01 -ScriptBlock {$PSVersionTable.PSVersion} -Credential $cred

получить версию powershell с удаленного компьютера

Major Minor Build Revision PSComputerName
----- ----- ----- -------- --------------
5 1 14393 3383 dc01

Можно получить установленные версии PowerShell с нескольких компьютеров таким скриптом (их список сохранен в текстовом файле):

Invoke-Command -ComputerName (Get-Content C:\PS\servers.txt) -
ScriptBlock{$PSVersionTable.PSVersion} | Select PSComputerName, @{N="PS Version";E={$_.Major}}

Либо можно получить список компьютеров домена через Get-ADComputer и получить версию PowerShell на них:

$adcomputer=(Get-ADComputer -Filter 'operatingsystem -like "*Windows server*" -and enabled -eq "true"' -SearchBase ‘OU=servers,dc=winitpro,dc=ru’ ).Name
Invoke-Command-ComputerName $adcomputer -Scriptblock{$PSVersionTable.psversion} -ErrorAction SilentlyContinue

Если ваш скрипт PoweShell использует специальный функционал определенной версии PS, вы можно принудительно переключиться в режим другой версии PowerShell. Например, для запуска консоли в режиме PowerShell v3, выполните (должен быть установлен .Net Framework 3.5):

PowerShell.exe -version 3

Определение версии PowerShell может быть важно при выполнении скриптов и запуске команд, которые используют командлеты или специальные возможности определенной версии PS. Если вы хотите в скрипте PS определить какая версия PowerShell установлена, и в зависимости от этого использовать разные командлеты, вы можете использовать такой скрипт:

$ps_version = $PSVersionTable.PSVersion.major
if ( $ps_version -eq "2” )
{
write "Вы используете Powershell 2.0"
}
elseif ( $ps_version -eq "5" )
{
write " Вы используете Powershell 5"
}

В следующей статье мы рассмотрим, как обновить версию PowerShell в Windows.

For any IT pro or developer working on Windows, learning PowerShell is a highly valuable investment of your time. As automation and agility continue to transform technology, PowerShell skills are becoming ubiquitous and foundational.

But like any technology, new PowerShell versions with useful improvements and fixes roll out periodically. So understanding how to check and update PowerShell smoothly is key for riding the automation wave both now and into the future!

In this comprehensive guide, we’ll cover all the key details around PowerShell updating, also providing some 101-style background for complete beginners along the way. Time to level up those PS mastery skills!

What Exactly is PowerShell And Why Does it Matter?

For those totally new to PowerShell, let’s first cover some quick background on what this tool actually is and why it’s grown so popular among systems administrators and engineers.

At a basic level, PowerShell is Microsoft’s advanced scripting language shell and task automation platform built directly into Windows machines. It allows you to control virtually every aspect of Windows through code, solving intricate challenges easily.

Some examples of what you can leverage PowerShell for:

  • Automating repetitive sysadmin tasks to save vast time
  • Building/managing complex infrastructure as code
  • Streamlining deployment workflows and application installs
  • Querying, manipulating, and reporting on system data
  • Integrating with APIs to manage cloud platforms like Azure
  • Containerizing workloads using Docker

And much more – the sky‘s really the limit!

PowerShell achieves all this through its robust framework of «cmdlets». These are essentially lightweight commands and functions tailored towards administration. Chaining them together creates seamless automation flows.

Beyond saving time and effort though, PowerShell also introduces stability, consistency and precision compared to manual clicking in GUIs. Infrastructure built through code is far easier to replicate, tweak and scale too.

With Microsoft expanding PowerShell support across Windows Server, desktop, cloud and more, skills in this area are becoming indispensable for unlocking efficiency.

Why Keeping PowerShell Updated Matters

Now that you understand the immense value of PowerShell for taming Windows environments, let‘s talk about why keeping your installation up-to-date is so important.

There are a few key reasons:

Access New Features

New major PowerShell releases introduce handy additional functionality like new cmdlets tailored towards automation tasks. Upgrading ensures you can leverage the latest tools.

Improve Reliability & Performance

From optimizations under the hood through to critical bug fixes, PowerShell updates vastly improve stability and speed. Outdated versions may suffer bottlenecks or issues.

Maintain Compatibility

As Microsoft products continue evolving, older PowerShell releases may lose backwards-compatibility. Upgrading prevents unexpected problems down the road.

Enhanced Security

New versions often contain vital security enhancements to guard against emerging threats. Running unsupported PowerShell leaves you vulnerable.

Simply put – sticking to an old PS version indefinitely is like driving a rusted old car. It might still work OK today, but roadblocks, slowness and safety issues are lurking right around the corner.

Taking a few minutes to check and upgrade PowerShell periodically is well worth avoiding those headaches!

Now let‘s explore how to do exactly that…

Checking Your Currently Installed PowerShell Version

When it comes to checking the specific PowerShell version running on your Windows Server or other host, the most reliable method is using the automatic $PSVersionTable variable.

Here is how to use in a glance:

  1. Launch a PowerShell console/terminal
  2. Type $PSVersionTable and press Enter
  3. Check the «PSVersion» value for the version number

For example, you may see output similar to:

Name                           Value
----                           ----- 
PSVersion                      5.1.14409.1018
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0...}
BuildVersion                   10.0.14409.1018
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

This makes clear we are running PowerShell version 5.1 on this system.

The key perk of using $PSVersionTable is reliability – it shows the exact PowerShell engine version, unlike some other popular techniques that may be inconsistent.

Now that you can easily check the installed version, let‘s look at actually updating it on Windows Server…

Upgrading Your PowerShell Version Painlessly

When you‘re ready to upgrade PowerShell to gain access to the latest capabilities, there are a couple straightforward options:

Downloading Manually from Microsoft

Your first choice is to manually download the newest PowerShell version‘s installer package from the official Microsoft website.

They provide easy step-by-step directions tailored to your Windows machine‘s environment. Generally it just involves:

  1. Grabbing the latest PowerShell MSI installer
  2. Running the installer, following prompts
  3. Testing functionality in a new PS terminal

One huge benefit of using the Microsoft packages is that they allow installing major PowerShell versions side-by-side.

For example, you could have PowerShell 7.5, PowerShell 5.9 and PowerShell 3 all usable simultaneously, without any conflicts. This gives flexibility.

Upgrading Via PowerShellGet Install Script

An alternative approach is to use the PowerShellGet install script to grab and deploy the latest version automatically.

You‘d run:

Install-Script -Name Install-PowerShell -Force
Install-PowerShell.ps1 [-UseMSI]

This downloads and kicks off execution of Install-PowerShell.ps1 from GitHub, handling the end-to-end upgrade process through prompts.

The script also supports installing multiple side-by-side versions cleanly. And you can easily tweak target channels like Release, Preview or LTS with parameters.

Overall, PowerShellGet provides an OS-tailored upgrading experience with just couple lines!

A Note About Compatibility Across Windows Editions

As a quick compatibility side note when upgrading PowerShell versions on older Windows editions:

Some legacy operating systems have restrictions…

Windows Version Highest PS Version Supported
Windows 7 SP1 5.1
Windows 8.1 5.1
Windows 10 Latest
Windows Server Latest

So for instance, trying to install PowerShell 7 or later inherently won‘t work properly on Windows 7.

Plan to upgrade the actual OS itself first in those cases. Up-to-date Windows 10 and Windows Server editions are aligned closely with recent PowerShell releases.

Closing Thoughts

Hopefully this guide has given both new PowerShell newcomers and savvy veterans a helpful 101-style primer related to checking installed PS versions and upgrading them smoothly on Windows systems.

Keeping your copy updated periodically is vital for continued stability, security and access to the rich new automation capabilities constantly being added across Microsoft‘s stacks.

PowerShell skills truly pay dividends across a IT career regardless of specialty – don‘t leave them stagnant!

Let us know if you have any other questions. And happy scripting!

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.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как настроить значки в трее windows 11
  • Мультизагрузочная флешка со всеми windows
  • Как поменять цвет панели управления в windows 10
  • Windows 10 домашняя настройка пользователей
  • Отваливается сетевой диск windows 10