Check OS with PowerShell

All information relative to the Operating System installed can be retrieved from the registry and more especially in the following key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion

.

Until Windows 8.1, the entry CurrentVersion could be used to retrieve the Windows OS version:

.

But, this entry is deprecated since Windows 10, and Microsoft recommends to use the following entries:

  • CurrentMajorVersionNumber (exists only on Win 10)
  • CurrentBuild
  • ProductName
  • ReleaseId (exists only on Win 10)

.

This PowerShell script does the following:

  • Check if the OS is Windows 7 (using the registry CurrentVersion)
  • If not Windows 7, check if the OS is Windows 10 (using the registry CurrentMajorVersionNumber)
## Check OS
Write-Host "----- Checking OS -----"
$CurVer = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").CurrentVersion
If ($CurVer -eq "6.1") {
	Write-Host "CurrentVersion registry value is 6.1, OS is Windows 7"
}
Else {
	Write-Host "CurrentVersion registry value is not 6.1, OS is not Windows 7"
	$MajVer = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").CurrentMajorVersionNumber
	If (($MajVer -eq $null) -or ($MajVer.Length -eq 0)) { 
		Write-Host "CurrentMajorVersionNumber registry entry does not exist, OS is not Windows 10"
	}
	Else {
		If ($MajVer -eq 10) { 
			$CurBuild = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").CurrentBuild
			$WinName = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ProductName
			$RelID = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ReleaseId
			Write-Host "CurrentMajorVersionNumber registry entry is 10, OS is Windows 10"
			Write-Host "Current Build is $CurBuild"
			Write-Host "Product Name is $WinName"
			Write-Host "Release ID is $RelID"
		}
		Else {
			Write-Host "CurrentMajorVersionNumber registry entry exists but is not equal to 10, OS is unknow at the time of the creation of this script..."
		}
	}
}