PowerShell script to retrieve the OperatingSystem and Service Pack

GetOSVersion.ps1

param( [string] $ServerName) 

"Server:$ServerName"

## check the machine is pingable
	
$query = "select * from win32_pingstatus where address = '$ServerName'"
$result = Get-WmiObject -query $query

if ($result.protocoladdress) {

	$build = @{n="Build";e={$_.BuildNumber}}
	$SPNumber = @{n="SPNumber";e={$_.CSDVersion}}
	$sku = @{n="SKU";e={$_.OperatingSystemSKU}}
	$hostname = @{n="HostName";e={$_.CSName}}

   $Win32_OS = Get-WmiObject Win32_OperatingSystem -computer $ServerName | select $build,$SPNumber,Caption,$sku,$hostname, servicepackmajorversion

   ## Get the Service pack level
   $servicepack = $Win32_OS.servicepackmajorversion

   ## Get the OS build

   switch ($Win32_OS.build) {
     ## the break statement will stop at the first match
     2600 {$os = 'XP'; break}
     3790 { if ($Win32_OS.caption -match 'XP') { $os = "XPx64" } else { $os = 'Server 2003' }; break }
     6000 {$os = 'Vista'; break}
     6001 { if ($Win32_OS.caption -match 'Vista' ) { $os = "Vista" } else { $os = 'Server 2008'}; break }
     }

   "Operating System: $os Service Pack: $servicepack"
   "Operating System: $os Service Pack: $servicepack" | out-file -filepath C:\ServicePack.txt
} else {
            "$ServerName Not Responding" }

Run the script above with:
PS C:\ ./GetOSVersion.ps1 MyServerName

“The hero has died as a modern man; but as eternal man - perfected, unspecific, universal man, - he has been reborn” ~ Joseph Campbell

Related:

Get-WMIobject - Get WMI class information
VER - Display version information
WQL (WMI Query Language) - msdn.microsoft.com


© Copyright SS64.com 1999-2013
Some rights reserved