How can I pull the value in Command in Powershell?

Viewed 59

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
3 Answers

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)

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

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
Related