Search code examples
powershellpowershell-2.0powershell-3.0

Is there way to know cmdlet version in Powershell for backward compatibility?


Say you are scripting in Powershell 4.0 environment and you want to make sure the script works in Powershell 3.0. How do you ensure its backward compatible?.


Solution

  • Ok the question as phrased is a little more specific into what you are looking for. Sounds like you are asking for requires.

    The#Requires statement prevents a script from running unless the Windows PowerShell version, modules, snap-ins, and module and snap-in version prerequisites are met. If the prerequisites are not met, Windows PowerShell does not run the script.

    That way, while you are scripting, you can enforce the functional version of your script.

    #Requires -Version 3.0
    

    So now while you are building and debugging your script you know that it will work on systems with at least 3.0. It recognizes minor builds as well if that matters.


    I recently came across this requirement for my own needs and realize now that what I suggested up above will not get you the exact results I think you are looking for. What you should do instead is when you run your script call a new PowerShell session and use the -Version switch which Starts the specified version of Windows PowerShell(TechNet).

    So when you are testing your script run it like this:

    powershell -Version 2 -File myscript.ps1