在Windows 8上使用PowerShell 2作为默认版本

wal*_*ido 7 powershell powershell-3.0

我想在Windows 8上使用PowerShell 2作为默认的PowerShell版本而不指定-Version开关.

我开始使用PowerShell 3附带的Windows 8 RTM,我的脚本与PowerShell 3不兼容.

lat*_*kin 6

Powershell使用发布者策略(请参见此处)自动将针对Powershell 2构建的主机重定向到Powershell 3运行时(如果可用).

大多数情况下,这正是您想要的,但是如果您的应用需要,您可以明确禁用发布商政策.

将其放在app.config文件中以禁用System.Management.Automation(powershell运行时)的发布者策略:

<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>
Run Code Online (Sandbox Code Playgroud)

测试它(针对.NET 4.0的控制台应用程序,明确引用PS v2运行时):

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);
Run Code Online (Sandbox Code Playgroud)

在我的Win8盒子上运行这个(PSv3肯定在那里),我得到了结果

Powershell version: 2.0
.NET version: 4.0.0.0
Run Code Online (Sandbox Code Playgroud)

如果我注释掉app.config,PS版本会变为3.0.