Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check powershell version and run a function based on the version

Tags:

powershell

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.

like image 831
Brum Avatar asked Jan 29 '23 00:01

Brum


1 Answers

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
like image 81
Bacon Bits Avatar answered May 20 '23 11:05

Bacon Bits