I want to learn the powershell version and write conditions accordingly, but I couldn't do it as I wanted.
"(Get-Host).Version | Select-Object major"
Output:
Major
-----
5
When I use the command, I guess it doesn't work because it shows as value under major. How can I get the value?
I tried something like this so I can get it as True or False, but it didn't work. It always returns false
if ( "(Get-Host).Version | Select-Object major" -eq "5" )
{
echo "True"
}
else
{
echo "False"
}
Output:
false
CodePudding user response:
Just replace
THIS
if ( "(Get-Host).Version | Select-Object major" -eq "5" )
{
echo "True"
}
else
{
echo "False"
}
With This:
if ( ((Get-Host).Version).Major -eq "5" )
{
echo "True"
}
else
{
echo "False"
}
CodePudding user response:
An object of the type System.Version is like any other object, it's properties can be referenced by .PropertyName
The most common way to get the values of the properties of an object is to use the dot method. Type a reference to the object, such as a variable that contains the object, or a command that gets the object. Then, type a dot (.) followed by the property name.
From about_Properties
PS /> $ver = [version]'1.0.1'
PS /> $ver
Major Minor Build Revision
----- ----- ----- --------
1 0 1 -1
PS /> $ver.Major -eq 1
True
PS /> $ver | Get-Member -MemberType Property
TypeName: System.Version
Name MemberType Definition
---- ---------- ----------
Build Property int Build {get;}
Major Property int Major {get;}
MajorRevision Property short MajorRevision {get;}
Minor Property int Minor {get;}
MinorRevision Property short MinorRevision {get;}
Revision Property int Revision {get;}
The condition would be:
if((Get-Host).Version.Major -eq 5)
{
'True'
}
else
{
'False'
}
CodePudding user response:
The version is already in the $PSVersionTable
variable.
PS C:\> $PSVersionTable.PSVersion
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 2 0
PS C:\> $PSVersionTable.PSVersion.Major
7