PowerShell #requires -version

February 10th, 2010 | Tags:

Recently, I saw someone that had developed a script on the CTP3 drop and was then having trouble running it on v1 of PowerShell.  Eventually it turned out that he was using v2 features in his script.  Most of you know that we are trying to keep the next version of PowerShell compatible with v1 and I encourage you to report any problems that you might have in that area.  Unfortunately, v2 being compatible with v1, doesn’t mean v1 is compatible with v2.

There are many ways you could annotate your scripts so people know what version they are supposed to be run on, but PowerShell already has a way to do it.  It’s called #requires.

In the majority of cases, all it will amount to is putting “#requires –version 2“  at the top of your script.  For example, here’s my awesome script that will only run on v2.

#requires -version 2

write-host “Can only run on v2.”

And here are the results on v2, followed by v1:

# V2

PS>.\foo.ps1

Can only run on v2.

# V1

PS > .\foo.ps1

The script ‘foo.ps1′ cannot be run because it contained a “#requires” statement at line 1 for Windows PowerShell version 2.0 which is incompatible with the installed Windows PowerShell version of 1.0.

At line:1 char:10

+ .\foo.ps1 <<<<

PS >

No comments yet.