title: Check powershell version and run a function based on the version
body: <p>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.</p>
  
  <pre><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"
  }
  </code></pre>
  
  <p>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. </p>
  
  <p><a href="https://i.stack.imgur.com/6MXlt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6MXlt.png" alt="enter image description here"></a></p>
  
  <p>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. </p>