Brum
Brum

Reputation: 55

Check powershell version and run a function based on the version

I'm trying to check the powershell version and based on what version, I need to run a specific function due to command and syntax differences between the different versions. I'm trying to create a variable with only the version number in it for easy comparison. Here's the code.

$PSversion = {$PSVersionTable.PSVersion | sort-object major | ForEach-Object     {$_.major}}

Switch ($PSversion) {
    2 {V2}
    4 {V4}
    5 {V5}
}

function V2 {
    "You have Powershell Version 2"
}

function V4 {
    "You have Powershell Version 4"
}

function V5 {
    "You have Powershell Version 5"
}

When I run the script it returns a blank line, when I print out the contents of the variable, I get the number and a new line. I've tried using replace to get rid of the new line but it's always there. If I enter the variable command directly into a powershell window, then print out the contents of the variable, I get the version number only, no new line. If I run the script from the same powershell window, I get nothing.

enter image description here

Any help on this would be appreciated! I don't have to use this method, any method to check the powershell version and run a function based on the version is all I'm looking for.

Upvotes: 5

Views: 15721

Answers (2)

air-dex
air-dex

Reputation: 4180

# Getting the whole Powershell version
$version = (Get-Host | Select-Object Version).Version

# Only the major one
$majvers = $version.Major

# The full version number (as a string)
$verstr = $version.toString()

Upvotes: 0

Bacon Bits
Bacon Bits

Reputation: 32145

In addition to @MathiasRJesson's comment about moving the functions to before they're being used, you're assigning a scriptblock to the $PSversion variable. It's not evaluating it.

This:

$PSversion = {$PSVersionTable.PSVersion | sort-object major | ForEach-Object     {$_.major}}

Should be:

$PSversion = $PSVersionTable.PSVersion | sort-object major | ForEach-Object     {$_.major}

Or could be just:

$PSversion = $PSVersionTable.PSVersion.Major

Upvotes: 9

Related Questions