繁体   English   中英

如何从 PowerShell 命令行查找 Windows 版本

[英]How to find the Windows version from the PowerShell command line

如何找到我正在使用的 Windows 版本?

我正在使用 PowerShell 2.0 并尝试过:

PS C:\> ver
The term 'ver' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify tha
t the path is correct and try again.
At line:1 char:4
+ ver <<<< 
    + CategoryInfo          : ObjectNotFound: (ver:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

我该怎么做呢?

由于您有权访问 .NET 库,因此您可以访问System.Environment类的OSVersion属性来获取此信息。 对于版本号,有Version属性。

例如,

PS C:\> [System.Environment]::OSVersion.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
6      1      7601   65536

可以在此处找到 Windows 版本的详细信息。

  1. 要获取 Windows 版本号,如 Jeff 在他的回答中指出的那样,请使用:

     [Environment]::OSVersion

    值得注意的是,结果是[System.Version]类型,因此可以检查 Windows 7/Windows Server 2008 R2 及更高版本

    [Environment]::OSVersion.Version -ge (new-object 'Version' 6,1)

    但是,这不会告诉您它是客户端还是服务器 Windows,也不会告诉您版本的名称。

  2. 使用 WMI 的Win32_OperatingSystem类(总是单实例),例如:

     (Get-WmiObject -class Win32_OperatingSystem).Caption

    会返回类似的东西

    Microsoft® Windows Server® 2008 标准版

不幸的是,大多数其他答案都没有提供特定于 Windows 10 的信息。

Windows 10 有自己的版本1507、1511、1607、1703 等 这就是winver显示的内容。

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

Command prompt (CMD.EXE):
Reg Query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ReleaseId

另请参阅有关超级用户的相关问题

至于其他 Windows 版本,请使用systeminfo Powershell 包装器:

PS C:\> systeminfo /fo csv | ConvertFrom-Csv | select OS*, System*, Hotfix* | Format-List


OS Name             : Microsoft Windows 7 Enterprise
OS Version          : 6.1.7601 Service Pack 1 Build 7601
OS Manufacturer     : Microsoft Corporation
OS Configuration    : Standalone Workstation
OS Build Type       : Multiprocessor Free
System Type         : x64-based PC
System Locale       : ru;Russian
Hotfix(s)           : 274 Hotfix(s) Installed.,[01]: KB2849697,[02]: KB2849697,[03]:...

相同命令的 Windows 10 输出:

OS Name             : Microsoft Windows 10 Enterprise N 2016 LTSB
OS Version          : 10.0.14393 N/A Build 14393
OS Manufacturer     : Microsoft Corporation
OS Configuration    : Standalone Workstation
OS Build Type       : Multiprocessor Free
System Type         : x64-based PC
System Directory    : C:\Windows\system32
System Locale       : en-us;English (United States)
Hotfix(s)           : N/A
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer

回报

WindowsProductName    WindowsVersion OsHardwareAbstractionLayer
------------------    -------------- --------------------------
Windows 10 Enterprise 1709           10.0.16299.371 
Get-WmiObject -Class Win32_OperatingSystem | ForEach-Object -MemberName Caption

或打高尔夫球

gwmi win32_operatingsystem | % caption

结果

Microsoft Windows 7 Ultimate

与上述所有解决方案不同,这将为您提供完整版本的 Windows(包括修订版/内部版本号)

(Get-ItemProperty -Path c:\windows\system32\hal.dll).VersionInfo.FileVersion

结果:

10.0.10240.16392 (th1_st1.150716-1608)

从 PowerShell 5 开始:

Get-ComputerInfo
Get-ComputerInfo -Property Windows*

我认为这个命令几乎尝试了迄今为止发现的 1001 种不同的方式来收集系统信息......

如果要区分 Windows 8.1 (6.3.9600) 和 Windows 8 (6.2.9200),请使用

(Get-CimInstance Win32_OperatingSystem).Version 

以获得正确的版本。 [Environment]::OSVersion在 Windows 8.1 中无法正常工作(它返回 Windows 8 版本)。

我正在完善其中一个答案

我在尝试匹配 w​​inver.exe 的输出时遇到了这个问题:

Version 1607 (OS Build 14393.351)

我能够使用以下命令提取构建字符串:

,((Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name BuildLabEx).BuildLabEx -split '\.') | % {  $_[0..1] -join '.' }  

结果: 14393.351

更新:这是一个使用正则表达式的稍微简化的脚本

(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").BuildLabEx -match '^[0-9]+\.[0-9]+' |  % { $matches.Values }

我采用了上面的脚本并对它们进行了一些调整以得出以下结果:

$name=(Get-WmiObject Win32_OperatingSystem).caption
$bit=(Get-WmiObject Win32_OperatingSystem).OSArchitecture

$vert = " Version:"
$ver=(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ReleaseId

$buildt = " Build:"
$build= (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").BuildLabEx -match '^[0-9]+\.[0-9]+' |  % { $matches.Values }

$installd = Get-ComputerInfo -Property WindowsInstallDateFromRegistry

Write-host $installd
Write-Host $name, $bit, $vert, $ver, `enter code here`$buildt, $build, $installd

要得到这样的结果:

Microsoft Windows 10 Home 64 位版本:1709 内部版本:16299.431 @{WindowsInstallDateFromRegistry=18-01-01 2:29:11 AM}

提示:如果有人从安装日期中删除前缀文本,我会很感激,这样我就可以用更易读的标题替换它。

除了其他答案之外,这里还有一些可以使用 PowerShell 检索的有用信息:

通过 PowerShell 查询操作系统和硬件信息:

查询通用OS(操作系统)信息:

查看操作系统名称的最快方法:

cmd ?

#Using 获取计算机信息:

Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer

#Using Get-WmiObject:

$name=(Get-WmiObject Win32_OperatingSystem).caption
$bit=(Get-WmiObject Win32_OperatingSystem).OSArchitecture
$ver=(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ReleaseId
Write-Host " OS-Name: `t $name `n Architct: `t $bit  `n Release: `t $ver" 

列出主要次要版本信息:

[System.Environment]::OSVersion.Version 

查询主机名:

$Env:ComputerName

要么

hostname    #cmd command

此外,如果您知道 IP 地址,请使用“ping”命令(例如: ping /a <your_ip_address> ),您将在第一行看到您的“主机名”。

查询当前(登录)用户:

whoami    #cmd command

要么

[System.Security.Principal.WindowsIdentity]::GetCurrent().Name 

查询映射驱动器:列出映射驱动器 - 使用 WMI:

Get-WmiObject -Class Win32_LogicalDisk | Format-Table 

要么

wmic logicaldisk get name       #list just logical-drive letters

或者,列出逻辑驱动器信息:FreeSpace、Provider(真实网络位置)、Size 和 VolumeName:

wmic logicaldisk list brief

列出映射的驱动器 - 使用 [DriveInfo] 类:

[System.IO.DriveInfo]::GetDrives()

列出可移动驱动器:

$drives = [System.IO.DriveInfo]::GetDrives()
$r = $drives | Where-Object { $_.DriveType -eq 'Removable' -and $_.IsReady }
if ($r) {
    return @($r)[-1]
}

查询磁盘容量、空间和卷类型

Invoke-Command -ComputerName S1 {Get-PSDrive C} | Select-Object PSComputerName,Used,Free 

可用空间:

(Get-PSDrive C).Free

或(以 GB 为单位)

[Math]::Floor(((Get-PSDrive C).Free /[Math]::Pow(2, 30)*10)) /10

已用空间:

(Get-PSDrive C).Used

或(以 GB 为单位的已用空间)

[Math]::Floor(((Get-PSDrive C).Used /[Math]::Pow(2, 30)*10)) /10

另外查看总空间:(以 GB 为单位)

$totalSpace = ((Get-PSDrive C).Used + (Get-PSDrive C).Free)/(1024*1024*1024)
OR
$totalSpace = ((Get-PSDrive C).Used + (Get-PSDrive C).Free)/[Math]::Pow(2, 30)

四舍五入值:

[Math]::Floor($totalSpace*10) / 10
OR
[Math]::Round($totalSpace,1)

查询主板信息:

wmic baseboard get product,Manufacturer,version,serialnumber

查询磁盘卷(磁盘分区)信息: Get-Volume 返回有关存储驱动器分区的信息,例如:

Get-Volume                 # All partitions
Get-Volume -DriveLetter C  # Specific partition

#文件系统类型:

Get-Volume -DriveLetter C | select FileSystem
(Get-Volume -DriveLetter C).FileSystem

#分区大小:

Get-Volume -DriveLetter C | select Size
OR (in GB)
[Math]::Floor(((Get-Volume -DriveLetter C).Size/[Math]::Pow(2, 30)*10)) /10

查询内存/查询RAM

Get-WmiObject Win32_PhysicalMemory | Measure-Object -Property Capacity -Sum
OR (in GB)
$memory = (Get-WmiObject Win32_PhysicalMemory | Measure -Property Capacity -Sum).Sum
$memory = [Math]::Floor(($memory/[Math]::Pow(2, 30)*10)) /10
$memory.ToString() + " gb"

#查询内存包括频率/速度:

Get-CimInstance win32_physicalmemory | Format-Table Manufacturer,Banklabel,Configuredclockspeed,Devicelocator,Capacity,Serialnumber –autosize

如前所述,这个答案超出了问题的范围,但对于那些希望使用 PowerShell 获得更多操作系统或硬件信息的人来说可能会有用。

要在 Windows 10 1809 上的 PowerShell v5 中生成与 winver.exe 相同的输出:

$Version = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\'
"Version $($Version.ReleaseId) (OS Build $($Version.CurrentBuildNumber).$($Version.UBR))"

采用:

Get-WmiObject -class win32_operatingsystem -computer computername | Select-Object Caption

正如 MoonStom 所说, [Environment]::OSVersion OSVersion 在升级的 Windows 8.1 上无法正常工作(它返回 Windows 8 版本): link

如果要区分 Windows 8.1 (6.3.9600) 和 Windows 8 (6.2.9200),可以使用(Get-CimInstance Win32_OperatingSystem).Version来获取正确的版本。 但是这在 PowerShell 2 中不起作用。所以使用这个:

$version = $null
try {
    $version = (Get-CimInstance Win32_OperatingSystem).Version
}
catch {
    $version = [System.Environment]::OSVersion.Version | % {"{0}.{1}.{2}" -f $_.Major,$_.Minor,$_.Build}
}

如果您试图破译 MS 在其修补站点上发布的信息,例如https://technet.microsoft.com/en-us/library/security/ms17-010.aspx

您将需要一个组合,例如:

$name=(Get-WmiObject Win32_OperatingSystem).caption $bit=(Get-WmiObject Win32_OperatingSystem).OSArchitecture $ver=(Get-ItemProperty "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion").ReleaseId Write-Host $name, $bit, $ver

微软 Windows 10 家庭版 64 位 1703

Windows PowerShell 2.0:

$windows = New-Object -Type PSObject |
           Add-Member -MemberType NoteProperty -Name Caption -Value (Get-WmiObject -Class Win32_OperatingSystem).Caption -PassThru |
           Add-Member -MemberType NoteProperty -Name Version -Value [Environment]::OSVersion.Version                     -PassThru

Windows PowerShell 3.0:

$windows = [PSCustomObject]@{
    Caption = (Get-WmiObject -Class Win32_OperatingSystem).Caption
    Version = [Environment]::OSVersion.Version
}

用于显示(两个版本):

"{0}  ({1})" -f $windows.Caption, $windows.Version 

这真的是一个很长的话题,可能是因为答案虽然正确,但并没有解决基本问题。 我遇到了这个网站:版本和内部版本号,它清楚地概述了 Microsoft Windows 世界中的内容。

由于我的兴趣是知道我正在处理哪个确切的 Windows 操作系统,因此我将整个版本彩虹放在一边,而是专注于 BuildNumber。 可以通过以下方式获得内部版本号:

([Environment]::OSVersion.Version).Build

或通过:

(Get-CimInstance Win32_OperatingSystem).buildNumber

无论您喜欢哪种方式,选择权都在您手中。 所以从那里我可以做一些事情:

    switch ((Get-CimInstance Win32_OperatingSystem).BuildNumber) 
{
    6001 {$OS = "W2K8"}
    7600 {$OS = "W2K8R2"}
    7601 {$OS = "W2K8R2SP1"}    
    9200 {$OS = "W2K12"}
    9600 {$OS = "W2K12R2"}
    14393 {$OS = "W2K16v1607"}
    16229 {$OS = "W2K16v1709"}
    default { $OS = "Not Listed"}

}
Write-Host "Server system: $OS" -foregroundcolor Green

注意:如您所见,我仅将上述内容用于服务器系统,但它可以轻松应用于工作站,甚至可以巧妙地扩展以支持两者……但我将把它留给您。

享受,玩得开心!

应该像这样简单:

Get-ComputerInfo  | select windowsversion
(Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name BuildLabEx).BuildLabEx

你们太努力了这适用于使用 Enter-PSSession 的本地或远程会话 - 试一试。

您所要做的就是输入:

cmd ?

Microsoft Windows [版本 10.0.19042.1237]

与所有其他解决方案(在 Windows 10 上测试)不同,这将为您提供完整且正确的(与您在运行 winver.exe 时找到的版本号相同)版本的 Windows(包括修订版/内部版本号):

Function Get-OSVersion {
Param($ComputerName)
    Invoke-Command -ComputerName $ComputerName -ScriptBlock {
        $all = @()
        (Get-Childitem c:\windows\system32) | ? Length | Foreach {

            $all += (Get-ItemProperty -Path $_.FullName).VersionInfo.Productversion
        }
        $version = [System.Environment]::OSVersion.Version
        $osversion = "$($version.major).0.$($version.build)"
        $minor = @()
        $all | ? {$_ -like "$osversion*"} | Foreach {
            $minor += [int]($_ -replace".*\.")
        }
        $minor = $minor | sort | Select -Last 1

        return "$osversion.$minor"
    }
}

我搜索了很多来找出确切的版本,因为 WSUS 服务器显示了错误的版本。 最好是从 UBR 注册表 KEY 获取修订版。

    $WinVer = New-Object –TypeName PSObject
$WinVer | Add-Member –MemberType NoteProperty –Name Major –Value $(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion' CurrentMajorVersionNumber).CurrentMajorVersionNumber
$WinVer | Add-Member –MemberType NoteProperty –Name Minor –Value $(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion' CurrentMinorVersionNumber).CurrentMinorVersionNumber
$WinVer | Add-Member –MemberType NoteProperty –Name Build –Value $(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion' CurrentBuild).CurrentBuild
$WinVer | Add-Member –MemberType NoteProperty –Name Revision –Value $(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion' UBR).UBR
$WinVer

使用Windows Powershell,可以通过以下方式获取你需要的数据

标题:

(Get-WmiObject -class Win32_OperatingSystem).Caption

发布 ID:

(Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ReleaseId).ReleaseId

版本:

(Get-CimInstance Win32_OperatingSystem).version

[解决了]

#copy all the code below:
#save file as .ps1 run and see the magic

 Get-WmiObject -Class Win32_OperatingSystem | ForEach-Object -MemberName Caption
 (Get-CimInstance Win32_OperatingSystem).version


#-------------comment-------------#
#-----finding windows version-----#

$version= (Get-CimInstance Win32_OperatingSystem).version
$length= $version.Length
$index= $version.IndexOf(".")
[int]$windows= $version.Remove($index,$length-2)  
$windows
#-----------end------------------#
#-----------comment-----------------#

您也可以通过检查 OSVersion.Version.Major 来使用类似的东西:

IF ([System.Environment]::OSVersion.Version.Major -ge 10) {Write-Host "Windows 10 or above"}
IF ([System.Environment]::OSVersion.Version.Major -lt 10) {Write-Host "Windows 8.1 or below"}

HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Update\\TargetingInfo\\Installed\\Client.OS.rs2.amd64\\Version 'For Win 10 Client'

HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Update\\TargetingInfo\\Installed\\Server.OS.amd64\\Version 'For Server OS'

(Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Update\TargetingInfo\Installed\Client.OS.rs2.amd64').version

根据蒂姆之前的回答,这个特定位置的好处是该物业已经采用我所说的首选格式。

我只想完成一个小脚本。 我们使用了之前回答过的switch版本,只是详细阐述了。 没有任何地方可以为您提供我们习惯的友好名称。 Windows 10 1909 或 Windows 10 20H2。 所以我们必须手动对它们进行编程。

$osversion = (Get-CimInstance -class Win32_OperatingSystem).Caption
$buildnumber = (Get-CimInstance Win32_OperatingSystem).BuildNumber
if($osversion -match "Windows 10")
{   
    switch ($buildnumber) 
    { 
        10240 {$OS = "Windows 10 1507"}
        10586 {$OS = "Windows 10 1511"}
        14393 {$OS = "Windows 10 1607"}
        15063 {$OS = "Windows 10 1703"}
        16299 {$OS = "Windows 10 1709"}
        17134 {$OS = "Windows 10 1803"}
        17763 {$OS = "Windows 10 1809"}
        18362 {$OS = "Windows 10 1903"}
        18363 {$OS = "Windows 10 1909"}
        19041 {$OS = "Windows 10 20H1"}
        19042 {$OS = "Windows 10 20H2"}
        19043 {$OS = "Windows 10 21H1"}
        default { $OS = "Not Listed"}
    }
}
if($osversion -match "Windows Server")
{
    switch ($buildnumber) 
    {
        3790 {$OS = "Windows Server 2003 R2"}
        6001 {$OS = "Windows Server 2008"}
        7600 {$OS = "Windows Server 2008 SP1"}
        7601 {$OS = "Windows Server 2008 R2"}    
        9200 {$OS = "Windows Server 2012"}
        9600 {$OS = "Windows Server 2012 R2"}
        14393 {$OS = "Windows Server 2016"}
        17763 {$OS = "Windows Server 2019"}
    }
}
Write-Host "Server system: $OS | $osversion | $buildnumber" -foregroundcolor Green

现在,如果您想一次扫描多台电脑,就像我想使用invoke-commandnew-pssession请注意Get-WMIObject已贬值并替换为get-ciminstance

如果您想要一个示例,我可以稍后提供 如果您使用的是 Windows 2003 R2 或更早版本.. 停止移动到新的操作系统。

PowerShell 中的 C:\\ 提示符或 cmd 提示符窗口中的 systeminfo 提供操作系统名称版本配置制造商等等...

相当于 winver 的 Powershell

适用于所有版本的 Windows 10,直到 20h2,速度快且不太复杂*

function Get-WinVer() {
    $win_release = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").displayversion
    if (!($win_release)) {
        $win_release = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ReleaseId}
    $win_release
}
Get-WinVer

它准确地显示了winver.exe在“版本”旁边显示的内容。

我没想到必须阅读这么多才能编写此代码,我真的希望我不必在 22h1(或当时的名称)中调整它。


*:微软肯定让它变得比它应该的更复杂

今天更正式的方法是使用这个:

Get-ComputerInfo | select WindowsProductName, OsOperatingSystemSKU, OsName | fl

# <output>
# WindowsProductName   : Windows 10 Home
# OsOperatingSystemSKU : WindowsHome
# OsName               : Microsoft Windows 10 Home

如果您想要其他项目,请查看以下列表:

(Get-CimInstance Win32_OperatingSystem) | select *

# ...
# and: 
(Get-CimInstance Win32_OperatingSystem).Caption

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

在 Windows 10 上返回:10.0.10586.420

然后,您可以使用该变量访问属性以进行粒度比较

$OSVersion.Major equals 10
$OSVersion.Minor equals 0
$OSVersion.Build equals 10586
$OSVersion.Revision equals 420

此外,您可以使用以下方法比较操作系统版本

If ([Version]$OSVersion -ge [Version]"6.1")
   {
       #Do Something
   }

您可以使用 python 来简化事情(适用于所有 Windows 版本和所有其他平台):

import platform

print(platform.system()) # returns 'Windows', 'Linux' etc.
print(platform.release()) # returns for Windows 10 or Server 2019 '10'

if platform.system() = 'Windows':
    print(platform.win32_ver()) # returns (10, 10.0.17744, SP0, Multiprocessor Free) on windows server 2019

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM