В статье рассмотрим несколько способов инвентаризации версии и билдов Windows (особенно актуально это для Windows 10) в домене Active Directory. Если у вас средств автоматизации сбора конфигураций компьютеров, например SCCM, GLPI c FusionInventory, или хотя бы сервер обновлений WSUS (он также позволяет показать версию Windows на обнаруженных компьютерах), вы можете использовать PowerShell скрипт для получения билдов Windows на компьютерах.
На отдельно-стоящем компьютере Windows можно получить номер билда из реестра или из SystemInfo:
Get-ItemProperty 'HKLM:SOFTWAREMicrosoftWindows NTCurrentVersion' | Select-Object ProductName, ReleaseID, CurrentBuild
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
Для получения списка активных компьютеров в домене Active Directory и версий (билдов) Windows на них можно использовать командлет Get-ADComputers.
Убедитесь, что на вашем компьютере установлен модуль Active Directory PowerShell и выполните команду:
Get-ADComputer -Filter {(Enabled -eq $True)} -Property * | Select-Object Name,OperatingSystem,OperatingSystemVersion
Чтобы преобразовать номер билда Windows 10 и 11 в более привычный формат (21H1, 21H2 и т.д.), нужно использовать дополнительную функцию.
function ConvertWindowsBuild{
[CmdletBinding()]
param(
[string] $OperatingSystem,
[string] $OperatingSystemVersion
)
if (($OperatingSystem -like '*Windows 10*') –or ($OperatingSystem -like 'Windows 11*')) {
$WinBuilds= @{
'10.0 (22000)' = "Windows 11 21H2"
'10.0 (19044)' = "Windows 10 21H2"
'10.0 (19043)' = "Windows 10 21H1"
'10.0 (19042)' = "Windows 10 20H2"
'10.0 (18362)' = "Windows 10 1903"
'10.0 (17763)' = "Windows 10 1809"
'10.0 (17134)' = "Windows 10 1803"
'10.0 (16299)' = "Windows 10 1709"
'10.0 (15063)' = "Windows 10 1703"
'10.0 (14393)' = "Windows 10 1607"
'10.0 (10586)' = "Windows 10 1511"
'10.0 (10240)' = "Windows 10 1507"
'10.0 (18898)' = 'Windows 10 Insider Preview'
}
$WinBuild= $WinBuilds[$OperatingSystemVersion]
}
else {$WinBuild = $OperatingSystem}
if ($WinBuild) {
$WinBuild
} else {
'Unknown'
}
}
Теперь, чтобы получить список версий Windows с названиями билдов, IP адресами, и датой последнего входа (регистрации) компьютера в домене, выполните следующий PowerShell скрипт:
$Comps= Get-ADComputer -Filter {(Enabled -eq $True)} -properties *
$CompList = foreach ($Comp in $Comps) {
[PSCustomObject] @{
Name = $Comp.Name
IPv4Address = $Comp.IPv4Address
OperatingSystem = $Comp.OperatingSystem
Build = ConvertWindowsBuild -OperatingSystem $Comp.OperatingSystem -OperatingSystemVersion $Comp.OperatingSystemVersion
LastLogonDate = $Comp.LastLogonDate
}
}
$CompList | Out-GridView
Результат предоставлен в виде таблицы Out-Gridview либо экспортировать в CSV (
Export-Csv -Path .win_builds_report.csv -NoTypeInformation
).
Чтобы вывести суммарную статистику по количеству компьютеров с разными версиями Windows в домене:
$CompList | Group-Object -Property Build | Format-Table -Property Name, Count
Также можно удаленно опрашивать компьютеры и получить версию Windows на них через PowerShell Remoting. Этот метод намного более медленный, но позволить получить версию Windows на компьютерах, которые находятся в рабочей группе (как через PSRemoting удаленно подключиться к компьютеру в рабочей группе). Для получения информации с удаленных компьютеров можно использовать командлет Invoke-Command:
Invoke-Command -ScriptBlock {Get-ItemProperty 'HKLM:SOFTWAREMicrosoftWindows NTCurrentVersion' | Select-Object ProductName, ReleaseID, CurrentBuild} -ComputerName wsk-w10BO1| Select-Object PSComputerName,ProductName, ReleaseID, CurrentBuild
Можно получить версию Windows на нескольких компьютеров по списку из txt файла:
Invoke-Command –ComputerName (Get-Content c:pscomps.txt) -ScriptBlock {Get-ItemProperty 'HKLM:SOFTWAREMicrosoftWindows NTCurrentVersion' | Select-Object ProductName, ReleaseID, CurrentBuild}|Select-Object PSComputerName,ProductName, ReleaseID, CurrentBuild
С помощью рассмотренных PowerShell скриптов вы сможете определить версии и билды Windows на компьютерах домена, найти компьютеры с устаревшими билдами Windows 10 и обновить их (пример обновления билда Windows 10 из командной строки).
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 "ComputerNameUserName" #$PSCredential = Get-Credential "DomainNameUserName" 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:Tempcomputers.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:TempOS_Details.csv" -NoTypeInformation -Encoding UTF8
Посмотреть в Powershell версию Windows можно с помощью WMI или отдельных командлетов. Самый простой способ — это запустить:
Get-ComputerInfo
Мы можем получить сразу через Powershell версию ОС, не выводя всю информацию:
(Get-ComputerInfo).WindowsVersion
#или
Get-ComputerInfo -Property *Version*
Минусом этого командлета является то, что он долго отрабатывает каждый раз подгружая всю информацию. Если нужно узнать версию ОС на сотнях ПК, то стоит использовать другой вариант.
Командлет выше появился в версии PS 5.1, так что если сомневаетесь запустите:
host
#или
$PSVersionTable
Таким образом мы можем узнать версию билда:
$PSVersionTable.BuildVersion
Или использовать:
[System.Environment]::OSVersion.Version
Как получить в Powershell версию Windows используя WMI
Через WMI мы можем вернуть практически любое значение ОС, так что нужно найти только нужный класс:
Get-WmiObject -List | where -Property Name -Like "win32_Oper*"
Класс, который вернет версию ОС называется «Win32_OperatingSystem»:
Get-WmiObject -Class Win32_OperatingSystem | fl -Property Version, BuildNumber
…
Теги:
#powershell
In addition to other answers, here are some useful information that can be retrieved using PowerShell:
Querying OS & Hardware Info via PowerShell:
Querying General OS (Operating System) Information:
Quickest way to view the OS name:
cmd ?
#Using Get-ComputerInfo:
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:SOFTWAREMicrosoftWindows NTCurrentVersion").ReleaseId
Write-Host " OS-Name: `t $name `n Architct: `t $bit `n Release: `t $ver"
To list Major Minor Version info:
[System.Environment]::OSVersion.Version
Querying HostName:
$Env:ComputerName
OR
hostname #cmd command
Also, if you know the IP address, use the «ping» command (e.g.: ping /a <your_ip_address>
) you will see your «hostname» in first line.
Querying Current (Logged-in) User:
whoami #cmd command
OR
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Querying Mapped Drives:
List Mapped Drives — using WMI:
Get-WmiObject -Class Win32_LogicalDisk | Format-Table
OR
wmic logicaldisk get name #list just logical-drive letters
OR, to list logical-drive info: FreeSpace, Provider (Real Network Location), Size, and VolumeName:
wmic logicaldisk list brief
List Mapped Drives — using [DriveInfo] class:
[System.IO.DriveInfo]::GetDrives()
List Removable Drives:
$drives = [System.IO.DriveInfo]::GetDrives()
$r = $drives | Where-Object { $_.DriveType -eq 'Removable' -and $_.IsReady }
if ($r) {
return @($r)[-1]
}
Querying disk capacity, space & Volume-Type
Invoke-Command -ComputerName S1 {Get-PSDrive C} | Select-Object PSComputerName,Used,Free
Free Space:
(Get-PSDrive C).Free
OR (in GB)
[Math]::Floor(((Get-PSDrive C).Free /[Math]::Pow(2, 30)*10)) /10
Used Space:
(Get-PSDrive C).Used
OR (Used space in GB’s)
[Math]::Floor(((Get-PSDrive C).Used /[Math]::Pow(2, 30)*10)) /10
Additionally to view total Space: (in 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)
Rounded off values:
[Math]::Floor($totalSpace*10) / 10
OR
[Math]::Round($totalSpace,1)
Querying Motherboard info:
wmic baseboard get product,Manufacturer,version,serialnumber
Querying Disk Volume (Of Disk Partitions) Info:
Get-Volume returns information about storage drive’s partitions, e.g.:
Get-Volume # All partitions
Get-Volume -DriveLetter C # Specific partition
#file system type:
Get-Volume -DriveLetter C | select FileSystem
(Get-Volume -DriveLetter C).FileSystem
#partition size:
Get-Volume -DriveLetter C | select Size
OR (in GB)
[Math]::Floor(((Get-Volume -DriveLetter C).Size/[Math]::Pow(2, 30)*10)) /10
Querying Memory / Query 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"
#Query RAM including Frequency / Speed:
Get-CimInstance win32_physicalmemory | Format-Table Manufacturer,Banklabel,Configuredclockspeed,Devicelocator,Capacity,Serialnumber –autosize
As mentioned, this answer goes bit beyond the question asked, but could be useful for those who’d like additional OS or Hardware information using PowerShell.
I’m trying to write a PowerShell script that I can run on remote servers. In these scripts I want to carry out different functions depending on which version of Windows is running on the machines.
I cant seem to find any useful information on the net about how to determine which version of Windows is running on the machine that the script is being run on (Server 2003, Server 2008 R2 etc). Any ideas how I can do this?
Gaff
18.3k15 gold badges56 silver badges68 bronze badges
asked Jul 14, 2011 at 10:36
4
This is the one I would go with:
gwmi win32_operatingSystem | select name
As todda.speot.is mentioned, that is the same link I found, but there are a lot of anwsers within it, and I tested them. That one I gave appears to give you what you want, although you will have to parse it (I think that is the right term).
Here is a sample output:
Microsoft Windows Server 2003 R2 Standard x64 Edition|C:WINDOWS|DeviceHarddisk0Partition1
http://www.eggheadcafe.com/software/aspnet/31845351/reliable-way-to-get-windows-version.aspx
answered Jul 14, 2011 at 10:52
KCotreauKCotreau
25.5k5 gold badges46 silver badges72 bronze badges
Get-WmiObject -Class Win32_OperatingSystem | ForEach-Object -MemberName Caption
Or golfed
gwmi win32_operatingsystem |% caption
Result
Microsoft Windows 7 Ultimate
answered May 13, 2014 at 2:55
I’d use:
gwmi win32_operatingSystem | select caption
No ‘parsing’ required. ;^)
Sample output:
Microsoft Windows Server 2003 R2 Standard x64 Edition
answered Aug 30, 2013 at 10:59
MicaHMicaH
191 bronze badge
I’m trying to write a PowerShell script that I can run on remote servers. In these scripts I want to carry out different functions depending on which version of Windows is running on the machines.
I cant seem to find any useful information on the net about how to determine which version of Windows is running on the machine that the script is being run on (Server 2003, Server 2008 R2 etc). Any ideas how I can do this?
Gaff
18.3k15 gold badges56 silver badges68 bronze badges
asked Jul 14, 2011 at 10:36
4
This is the one I would go with:
gwmi win32_operatingSystem | select name
As todda.speot.is mentioned, that is the same link I found, but there are a lot of anwsers within it, and I tested them. That one I gave appears to give you what you want, although you will have to parse it (I think that is the right term).
Here is a sample output:
Microsoft Windows Server 2003 R2 Standard x64 Edition|C:WINDOWS|DeviceHarddisk0Partition1
http://www.eggheadcafe.com/software/aspnet/31845351/reliable-way-to-get-windows-version.aspx
answered Jul 14, 2011 at 10:52
KCotreauKCotreau
25.5k5 gold badges46 silver badges72 bronze badges
Get-WmiObject -Class Win32_OperatingSystem | ForEach-Object -MemberName Caption
Or golfed
gwmi win32_operatingsystem |% caption
Result
Microsoft Windows 7 Ultimate
answered May 13, 2014 at 2:55
I’d use:
gwmi win32_operatingSystem | select caption
No ‘parsing’ required. ;^)
Sample output:
Microsoft Windows Server 2003 R2 Standard x64 Edition
answered Aug 30, 2013 at 10:59
MicaHMicaH
191 bronze badge
Иногда требуется оперативно получить информацию о системе, например тип операционной системы, модель процессора, количество оперативной памяти и т.п. Cегодня я опишу пару способов получения системной информации с помощью PowerShell.
Systeminfo
Утилита командной строки Systeminfo выдает подробную информацию о системе, включая установленные обновления. Вывод утилиты не очень информативный, поэтому для удобства его можно отформатировать с помощью PowerShell. Для этого вывод оформляется в формате CSV, затем с помощью командлета ConvertFrom-Csv преобразуется в объект и помещается в переменную:
$systeminfo = systeminfo /FO csv | ConvertFrom-Csv
После такого преобразования необходимые параметры можно запрашивать как свойства объекта. Данные можно выводить как поодиночке, так и в виде списка. Например так можно узнать время последней перезагрузки компьютера:
$systeminfo.’System Boot Time’
А так информацию об установленной на нем операционной системе:
$systeminfo | fl OS*
Для получения данных с удаленного компьютера у systeminfo имеется ключ /S, также при необходимости можно указать имя пользователя (/U) и пароль (/P). Для примера выведем данные о потреблении памяти на компьютере testdc2:
$systeminfo = systeminfo /FO csv /S testdc2 /U administrator /P ′p@$$w0rd′ | ConvertFrom-Csv
$systeminfo | fl *memory
Примечание. Если пароль содержит служебные символы (например знак $), то его необходимо заключать в одинарные кавычки. При использовании двойных кавычек будет выдана ошибка.
WMI
Windows Instrumentation Instrumentation (WMI) позволяет узнать практически любую информацию о компьютере. Базовую информацию о системе можно получить с помощью WMI-класса Win32_OperatingSystem (CIM_OperatingSystem). Для примера уточним данные об операционной системе:
$systeminfo = Get-CimInstance -ClassName Win32_OperatingSystem
$systeminfo | fl Caption, Version, BuildType, BuildNumber, InstallDate
Если требуется подробная информация об одном из компонентов системы, то можно использовать другие классы WMI. Перечисление и подробное описание классов WMI и CIM можно найти на MSDN, а мы для примера выведем свойства процессора с помощью класса Win32_Processor (CIM_Processor):
$cpuinfo = Get-CimInstance -ClassName CIM_Processor
$cpuinfo | fl Name, Description, Version
Для получения данных с удаленных систем можно в команде указать имя компьютера. Если компьютеров несколько, то имена указываются через запятую. Например:
$systeminfo = Get-CimInstance -ClassName CIM_OperatingSystem -ComputerName testdc1, testdc2
$systeminfo | ft PSComputerName, Caption, MUILanguages -a
Если же требуется указать учетные данные, то можно использовать другой подход. Сначала создаем удаленные сессии ко всем компьютерам, с которых надо получить данные:
$session = New-CimSession -ComputerName testdc1,testdc2 -Credential $(Get-Credential)
А затем используем созданные сессии для получения системной информации:
$systeminfo = Get-CimInstance -ClassName CIM_OperatingSystem -CimSession $session
$systeminfo | ft PSComputerName, Caption, MUILanguages -a
- Remove From My Forums
-
Вопрос
-
Здравствуйте!
Мне нужно получить список серверов и сделать действия, в зависимости разрядности ОС. Список компьютеров получаю с помощью инструментов quest software: get-qadcomputer. В свойствах возвращаемых объектах разрядности нет. По версии windows тоже нужное не определить.
Смотрел на wmi, но свойства OSArchitecture класса win32_operatingsystem на системах Windows 2003 нет. Я так понимаю, что проверять класс win32_processor нельзя, он относится к процессору, а не ос.В общем, сабж: как узнать разрядность ОС на powershell для удаленной машины?
Спасибо.
Ответы
-
Win32_OperatingSystem.Name
(Get-WmiObject Win32_OperatingSystem -computer «Имя компа»).name
или — Get-WmiObject Win32_OperatingSystem -property name -computer «имя компа»
Win32_OperatingSystem.OtherTypeDescription(Get-WmiObject Win32_OperatingSystem -computer «Имя компа»).OtherTypeDescription
или — Get-WmiObject Win32_OperatingSystem -property OtherTypeDescription -computer «имя компа»
Если ответ Вам помог, нажмите на изображение зеленой галочки — «пометить как ответ». Если ответ был для Вас полезен, Вы можете пометить это сообщение как «полезное», нажав на ссылку «проголосовать за полезное сообщение» в правом верхнем углу сообщения.
-
Изменено
29 июля 2009 г. 12:06
-
Помечено в качестве ответа
Борис Прол
30 июля 2009 г. 8:27
-
Изменено
-
(Get-WmiObject Win32_ComputerSystem -computer pc1).systemtype
AKA Xaegr, MCSE: Security, Messaging; MCITP: ServerEnterprise Administrator; Блог: http://xaegr.wordpress.com
-
Предложено в качестве ответа
Vasily GusevModerator
24 июля 2009 г. 7:37 -
Помечено в качестве ответа
Борис Прол
24 июля 2009 г. 7:59
-
Предложено в качестве ответа