2

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
Grau
  • 73
  • 5
  • 1
    [This answer](https://stackoverflow.com/a/48809321/45375) may also be of interest - it discusses various ways of extracting a single property _value_ from command output; if you use `Select-Object` (not really necessary in your case), you must use `Select-Object -ExpandProperty major`. – mklement0 Dec 12 '21 at 17:23

3 Answers3

3

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"
 }

Note: Get-Host is just the PS Host version. It might not be the PS Engine version. The engine version comes from $PSVersionTable.PSVersion. So, my recommendation for you is to use $PSVersionTable.PSVersion.Major instead of (((Get-Host).Version).Major)

Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45
2

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'
}
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
2

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
lit
  • 14,456
  • 10
  • 65
  • 119