5

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.

3
  • 2
    Move the switch statement to after the functions have been defined Commented Dec 20, 2017 at 16:20
  • 4
    Also an improvement: Switch ($PSVersionTable.PSVersion.Major) Commented Dec 20, 2017 at 16:23
  • 1
    General comment on this approach: it is better to check whether specific property, function or whatever exist than presuming it based on the version. I also recomment you to have a look at the #Requires directive. Commented Dec 20, 2017 at 17:22

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

Comments

0
# 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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.