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"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
srk786
  • 551
  • 3
  • 10
  • 19

1 Answers1

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

alroc
  • 27,574
  • 6
  • 51
  • 97
  • 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 – srk786 Oct 13 '14 at 12:56
  • Did you prefix `requires` with `#`? That's required as well, as seen in the examples in the link (and the code) I gave. – alroc Oct 13 '14 at 12:57
  • its running thanks, but i didnt understand # is for comments how come its running as a command or directives – srk786 Oct 13 '14 at 13:00
  • In this context, it's not a comment. – alroc Oct 13 '14 at 13:02