Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure that we are using powershell 2.0?

We are providing scripts to clients that will be working only in Powershell 2.0.

Through command we can ensure that powershell 2.0 is installed like below

$version = Get-host | Select-object Version

But if we provide script how to ensure that they are executing it from Powershell 2.0?

When executing the script , Powershell 2.0 features may give script errors while initiating the script itself.Isn't it?

like image 914
Samselvaprabu Avatar asked Aug 02 '12 05:08

Samselvaprabu


People also ask

How can I tell if PowerShell is enabled?

Check PowerShell Remoting is enabledWhen you run the Test-WSMan command on a local computer then you can see if PowerShell Remoting is enabled or not. Of course, you can run the command for another computer by using the -ComputerName parameter.

How do I disable PowerShell v2?

Windows Server 2016 or later: Open the “Server Manager”, and click on the “Manage > Remove Roles & Features”. On the Remove Features screen, expand Windows PowerShell and uncheck the “Windows PowerShell 2.0 Engine”. Click Next and Uninstall.


2 Answers

You can annotate your script with #requires and state that it shouldn't run on anything less than PowerShell v2:

#requires -Version 2.0

(Side note: This is surprisingly hard to find even if you know vaguely that it exists.)

like image 148
Joey Avatar answered Oct 18 '22 17:10

Joey


Relying on the host version is not the safest thing to do as the script can be run on hosts that do not have the same host version as PowerShell's version.

The $PSVersionTable variable was added in v2. You can check if the variable exists, if it does you're running v2 and above, you can also check PSVersion.Major property:

if($PSVersionTable)
{
    'PowerShell {0}' -f $PSVersionTable.PSVersion.Major
}
else
{
   'PowerShell 1'
}
like image 38
Shay Levy Avatar answered Oct 18 '22 16:10

Shay Levy