Using PowerShell 2 as the default version on Windo

2019-01-27 22:14发布

I would like to use PowerShell 2 as the default PowerShell version on Windows 8 without specifying the -Version switch.

I started using Windows 8 RTM which comes with PowerShell 3, and I have scripts that are not compatible with PowerShell 3.

2条回答
趁早两清
2楼-- · 2019-01-27 22:36

Powershell uses a publisher policy (see here also) to automatically redirect hosts built against Powershell 2 onto the Powershell 3 runtime if it's available.

Most of the time this is exactly what you want, however you can explicitly disable the publisher policy if needed for your app.

Put this in your app.config file to disable the publisher policy for System.Management.Automation (powershell runtime):

<configuration>
  <runtime>
     <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
       <dependentAssembly>
         <assemblyIdentity name="System.Management.Automation" publicKeyToken="31bf3856ad364e35" />
         <publisherPolicy apply="no" />
      </dependentAssembly>
     </assemblyBinding>
  </runtime>
</configuration>

Testing it out (console app targeted to .NET 4.0, with explicit reference to PS v2 runtime):

PowerShell ps = PowerShell.Create();
ps.AddScript("$psversiontable");
var result = ps.Invoke()[0].BaseObject as Hashtable;

Console.WriteLine("Powershell version: {0}", result["PSVersion"]);
Console.WriteLine(".NET version: {0}", typeof(string).Assembly.GetName().Version);

Running this on my Win8 box (PSv3 definitely there), I get result of

Powershell version: 2.0
.NET version: 4.0.0.0

And PS version goes to 3.0 if I comment out app.config.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-27 23:00

You say you have a custom application that hosts PowerShell and that the scripts are embedded in the application. Let's assume this application is called "MyApp.exe." Now, PowerShell 3.0 requires .NET 4.0 (CLR4), so the way to force the application to use PowerShell 2.0 is to force your application to use .NET 3.5 (CLR2). This will cause it to load the 1.0.0.0 version of System.Management.Automation instead of the 3.0.0.0 version which is for CLR4 only. Create a "MyApp.exe.config" in the same folder as the application with the following contents:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration>
 <startup>
  <supportedRuntime version="v2.0.50727"/>
 </startup>
</configuration>

Now, if your application was built against CLR4 and PowerShell 2.0, then you're in a bit more trouble. Hopefully this is not the case.

查看更多
登录 后发表回答