学习 PowerShell 中获取 Windows 版本的多种方式

故障排除系统并需要快速获取Windows版本?幸运的是,您可以使用PowerShell来获取您所在的Windows版本。

检查您使用的Windows版本是管理系统的重要步骤。在本教程中,您将学习到许多获取Windows版本的方法以及更多内容。

继续阅读并自行决定哪种方法最适合您!

先决条件

本教程将进行实际演示。要跟随操作,请确保您拥有一个Windows系统。本教程使用带有PowerShell 7的Windows 11。

使用PowerShell获取Windows版本

在使用PowerShell处理复杂事务之前,先从基础知识开始,比如获取系统信息。使用PowerShell,您可以通过systeminfo命令快速获取Windows版本。

打开您的PowerShell,并运行以下命令以获取关于您的系统的详细信息,包括操作系统(OS)版本。

systeminfo.exe

下面,您可以看到关于操作系统的详细信息,包括当前版本号,10.0.22622 N/A Build 22622

Getting the Windows version via the SystemInfo

选择特定属性以获取Windows版本

太好了!您刚刚检索了详细的系统信息。但如果仔细看,命令很短,但输出似乎很多。

如果您只想要特定的属性值,则Get-ComputerInfo命令是获取特定系统信息(如Windows版本)的最快方法之一。

运行以下命令以获取Windows版本、产品名称以及Windows内核版本和系统硬件操作硬件抽象(OHA)的版本。

在下面,将Select-Object命令与Get-ComputerInfo命令进行管道传递,可以仅检索选择的属性。

Get-ComputerInfo | Select-Object OSName, OSVersion, OsHardwareAbstractionLayer

正如您所见,安装了Windows 10 Pro,其版本为2009。

Getting the Windows version with the Get-ComputerInfo command

通过System.Environment类检索Windows版本的另一种方法

获取Windows版本的另一种方法是通过System.Environment类。该类提供对系统信息的访问,例如操作系统版本、用户名和其他环境变量。

System.Environment类还有一个名为OSVersion的属性,其中包含有关当前操作系统的信息。

运行以下命令来调用`System.Environment`类中的`OSVersion.Version`属性。双冒号(`::`)符号用于调用类中的静态方法。

[System.Environment]::OSVersion.Version

如下所示,输出显示操作系统版本信息:

Property Value Description
Major 10 Despite saying 10, this may indicate Windows 10 or 11 as both use the same Major version.
Minor 0 There are two types of Windows releases, major and minor. Major releases are the “big” updates like the Creator update, and minor releases are smaller cumulative updates.
Build 22622 The number used to check the Windows version. In this case, it is for version 22H2.
Revision 0 Denotes a sub-version of the build.
Getting the windows via the System.Environment class

挖掘特定属性以获取Windows版本

PowerShell cmdlet提供了关于系统的大量信息。但是,如果您只打算获取您的Windows版本,则`Get-ItemProperty` cmdlet是另一种选择。此cmdlet命令允许您访问注册表并从中获取各种属性。

运行以下命令来访问注册表(`Get-ItemProperty`)并检索当前Windows版本的`DisplayVersion`:HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion。显示版本(发布ID已弃用)是每个Windows版本的唯一标识符。

(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").DisplayVersion

下面的命令检索并打印当前Windows版本,即22H2。

Getting the Windows version via the Get-ItemProperty command

查询当前Windows版本

您已经看到如何访问属性以获取您当前的Windows版本。而且,当您涉及属性时,请招呼`Get-CimInstance` cmdlet。

Get-CimInstance cmdlet是通过查询Windows管理工具(WMI)对象来获取Windows版本的另一种方式。这样做可以让您访问系统硬件的各种属性。

运行以下命令来查询(Get-CimInstanceWin32_OperatingSystem类(一个WMI对象)以获取当前Windows .versionWin32_OperatingSystem类提供有关操作系统的信息。

(Get-CimInstance Win32_OperatingSystem) | Select-Object Caption, Version

如下所示,此输出与使用System.Environment类类似。但这次,您只会获得实际的操作系统版本,而不包括属性标题。修订版本也被省略,因为它在WMI对象中不可用。

Querying WMI for the current Windows version

结论

在本教程中,您已经学习了在PowerShell中获取当前Windows版本的众多方法。在PowerShell中检查Windows版本是一项有价值的技能。无论您是在解决系统问题还是检查应用程序与当前操作系统的兼容性,这项技能都可能很有用。

现在,为什么不创建一个用于检查Windows版本的脚本呢?也许可以安排一个定期运行脚本的任务呢?

Source:
https://adamtheautomator.com/powershell-to-get-the-windows-version/