1

I am writing a script which check the version of PowerShell. If it's version 4 then proceed, otherwise stop the execution. What I am trying to achieve here is I have five scripts in a folder which are run in order. I would like to put a PowerShell script right at the top which checks the version.

Here is my code:

$psversion= $psversiontable if($psversion -eq 4.0) { ./01. Run All Script.ps1 } 

"Run All Script" runs the rest of the scripts in order, so I would like to give PowerShell script as 02. check_psversion.ps1

requires -version 4 write-host "this is your version" 
2
  • requires must have a hash mark (#) in front of it. Commented Oct 13, 2014 at 12:58
  • Related post - Determine installed PowerShell version Commented Feb 17, 2021 at 11:36

1 Answer 1

6

You don't need to write any if tests; use the requires directive in all of your scripts (never assume or depend upon execution order, be explicit in each script).

#requires -version 4 

If you attempt to execute the script on version 3 or earlier, it will stop because of the requires directive.

Edit: To get the Powershell version number, use $psversiontable.psversion.major, unless you need finer resolution (exact build number).

Sign up to request clarification or add additional context in comments.

4 Comments

i created a dummy script with two line requires -version 5 and than a write host line but i am getting this error requires is not recognized as the name of cmdlet
Did you prefix requires with #? That's required as well, as seen in the examples in the link (and the code) I gave.
its running thanks, but i didnt understand # is for comments how come its running as a command or directives
In this context, it's not a comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.