What OS am I executing on? What bitness? Some Handy Functions to Use
Sometimes, it's important to know what OS you are running on, and/or how many bits that OS has. Here are some useful functions which can be reused in other Powershell scripts (a future post may include putting such things into a Powershell Module). Please note that this hasn't been 100% tested on all of the OSes identified, but should work*.
The other two functions are about detecting bitness - Get-OSBitness() will tell you if you are on a 64-bit or 32-bit OS, and Get-CurrentProcessBitness() will tell you what the current Powershell execution-engine is (ie you can detect if you are running on the 32-bit powershell.exe on a 64-bit OS). I can't really image G-CPB() being used much, but here it is anyway.
* Please also note that the Win8.1/2012R2 detection is known to be sometimes incorrect, and these OSes can instead show up as Win8/2012 (respectively); this is because Microsoft broke the detection mechanism in these OSes, and each application now must use a manifest.xml file to flag itself as a Win8.1/2012R2 app (as ooposed to a legacy <= Win8) - I'm pretty sure Powershell.exe is properly manifested and should detect as Win8.1, but the default Powershell ISE is not (at this current time) and will show Win8.
Function Get-OSVersion() {
# Version numbers as per http://www.gaijin.at/en/lstwinver.php
$osVersion = "Version not listed"
$os = (Get-WmiObject -class Win32_OperatingSystem)
Switch (($os.Version).Substring(0,3)) {
"5.1" { $osVersion = "XP" }
"5.2" { $osVersion = "2003" }
"6.0" { If ($os.ProductType -eq 1) { $osVersion = "Vista" } Else { $osVersion = "2008" } }
"6.1" { If ($os.ProductType -eq 1) { $osVersion = "7" } Else { $osVersion = "2008R2" } }
"6.2" { If ($os.ProductType -eq 1) { $osVersion = "8" } Else { $osVersion = "2012" } }
# 8.1/2012R2 version detection can be broken, and show up as "6.2", as per http://www.sapien.com/blog/2014/04/02/microsoft-windows-8-1-breaks-version-api/
"6.3" { If ($os.ProductType -eq 1) { $osVersion = "8.1" } Else { $osVersion = "2012R2" } }
}
return $osVersion
}
Function Get-CurrentProcessBitness() {
# This function finds the bitness of the powershell.exe process itself (ie can detect 32-bit powershell.exe on a win64)
$thisProcessBitness = 0
switch ([IntPtr]::Size) {
"4" { $thisProcessBitness = 32 }
"8" { $thisProcessBitness = 64 }
}
return $thisProcessBitness
}
Function Get-OSBitness() {
# This function finds the bitness of the OS itself (ie will detect 64-bit even if you're somehow using 32-bit powershell.exe)
$OSBitness = 0
switch ((Get-WmiObject Win32_OperatingSystem).OSArchitecture) {
"32-bit" { $OSBitness = 32 }
"64-bit" { $OSBitness = 64 }
}
return $OSBitness
}
I highly recommend Rob Van der Woulde's Scripting web site, for all sorts of tips and tricks like this in many scripting languages.
ReplyDeletehttp://www.robvanderwoude.com/