Reputation: 13
I'm writing a function for getting the Windows version using WMI object. But I wanted to add the Windows 10 ReleaseId ("1709") (from a registry key) into the object.
Is this a stupid idea? (It works, I just don't know if it's a smart thing to do.)
function Get-OSVersion {
[version]$OSVersion = (Get-WmiObject -Class Win32_OperatingSystem).Version
if ($OSVersion.Major -ge '10') {
$OSVersion | Add-Member -MemberType NoteProperty -Name ReleaseId -Value $([int]::Parse($(Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" ReleaseId).ReleaseId)) -Force
}
return $OSVersion
}
$OSVersion = Get-OSVersion
if ($OSVersion -ge '6.1') {"At least Win7"} else {"Too old"}
if ($OSVersion.ReleaseID -ge '1703') {"At least 1703."} else {"Too old"}
Also, would it be unwise to overwrite the member "Revision" (value is always -1) instead of adding a new member "ReleaseId"?
Upvotes: 1
Views: 401
Reputation: 200373
My recommendation would be to use calculated properties:
function Get-OSVersion {
Get-WmiObject -Class Win32_OperatingSystem |
Select-Object @{n='Version';e={[version]$_.Version}},
@{n='ReleaseId';e={
if (([version]$_.Version).Major -ge '10') {
[int](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ReleaseId
}
}}
}
Upvotes: 2
Reputation: 19684
To expand on my comment:
I wouldn't suggest changing a wmi class that you don't need to, but you're not doing that. I don't see anything wrong about your approach besides adding a member to a defined standard library class (
System.Version
) and doing a number comparison against a string.
What I would suggest doing is creating a [pscustomobject]
with the members you need:
function Get-OSVersion {
$OSVersion = [version](Get-CimInstance -ClassName Win32_OperatingSystem).Version
if ($OSVersion.Major -ge 10) {
[pscustomobject]@{
Version = $OSVersion
ReleaseId = [int](Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ReleaseId
}
} else {
[pscustomobject]@{
Version = $OSVersion
}
}
}
In use:
$OS = Get-OSVersion
if ($OS.Version -ge [version]'6.1') {
'At least Win7'
} else {
'Too old'
}
if ($OS.ReleaseId -ge 1703) {
'At least 1703.'
} else {
'Too old'
}
To serve an alternative: Use a hashtable since it looks like you're just doing key/value accessing and comparisons without any method implementation.
function Get-OSVersion {
$OS = @{
Version = [version](Get-CimInstance -ClassName Win32_OperatingSystem).Version
}
if ($OS.Version.Major -ge 10) {
$OS['ReleaseId'] = [int](Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ReleaseId
}
return $OS
}
Upvotes: 2