yantaq
yantaq

Reputation: 4038

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?.

Upvotes: 6

Views: 5035

Answers (3)

Genlight
Genlight

Reputation: 16

using get-module of the required Command, you can do it like:

(Get-Module (Get-Command Get-NetTCPConnection).Source).PowerShellVersion

For clarification:

  • (Get-command <your cmdlet>). Source gives you the installed location

Upvotes: 0

Matt
Matt

Reputation: 46710

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

Upvotes: 4

Buxmaniak
Buxmaniak

Reputation: 478

Here an example to get the Version of "Get-ChildItem":

(Get-Command Get-ChildItem).Version

Upvotes: 5

Related Questions