PowerShell,确定我们是否在运行Windows 10或Windows 11操作系统

4
如果我在Windows 10或Windows 11上运行以下版本测试,则它们都会将“$Major”报告为10,“$Minor”报告为0,因此此测试不足以确定我们是否在Windows 10或Windows 11上运行。
[version]$OSVersion = [Environment]::OSVersion.Version
$Major = $OSVersion.Major
$Minor = $OSVersion.Minor

# Other ways to test:

# $OSVersion = [Version](Get-ItemProperty -Path "$($Env:Windir)\System32\hal.dll" -ErrorAction SilentlyContinue).VersionInfo.FileVersion.Split()[0]

# [version]$OSVersion = Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty Version


在PowerShell中,我们如何区分是否在运行Windows 10或Windows 11?
2个回答

3

直接使用WMI数据需要较低的开销

$isWin11 = (Get-WmiObject Win32_OperatingSystem).Caption -Match "Windows 11"

2
在维基百科上,你可以找到一个包含版本号列表和它们所属操作系统版本信息的列表。通过使用这些信息,你可以通过比较[Environment]::OSVersion.Version.Build属性来确定操作系统版本。
此外,Get-ComputerInfo cmdlet会返回一个字符串形式的OSName,例如:

Microsoft Windows 11 Pro

您可以使用-match运算符来检查字符串是否包含“11”:
(Get-ComputerInfo | Select-Object -expand OsName) -match 11

这在大多数情况下应该可以工作,但我怀疑这可能不是最佳选择。


从构建编号构建列表似乎会随着新的构建编号的出现而失败,但感谢Get-ComputerInfo方法,它非常有效,但似乎速度相当慢,因为它必须处理Get-ComputerInfo详细信息中的所有内容(我猜这与systeminfo命令执行的操作相同)。如果我们可以找到生成OsName的确切方法,那就太完美了。我在注册表中进行了“Microsoft Windows 10 Pro”的全文搜索,但该文本不存在。 - YorSubs
2
为了以更具体的方式获取信息,您可以执行以下操作:get-ciminstance -query "select caption from win32_operatingsystem" 或者在 If 语句中使用它:If (get-ciminstance -query "select caption from win32_operatingsystem where caption like '%Windows 11%'"){} - Toni
可以使用 get-computerinfo -Property OsName 命令,但奇怪的是,它仍会查询许多不相关的信息,如 CPU 和网络信息 :(. - zett42

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接