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.
After seeing that, I started thinking about people sharing v2 scripts on the web and the problems they might cause someone that didn’t realize the script was supposed to be run on v2. If you are sharing your v2 scripts (and I hope you are), then I wanted to say two things. Firstly, thanks! Sharing scripts helps the community tremendously. Secondly, if they are meant to be run only on v2, be sure to annotate them so people don’t get into trouble trying to run them on v1.
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. You can read all about it here or here. I’m sure there are other places too, those are just the first ones I found.
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:
Can only run on v2.
PS > .\foo.ps1
The script ‘foo.ps1′ cannot be run because it contained a “#requires” statement at line 1 for Windows PowerShell versi
on 2.0 which is incompatible with the installed Windows PowerShell version of 1.0.
At line:1 char:10
+ .\foo.ps1 <<<<
- Marcel Ortiz Soto [MSFT]