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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With