我正在更新一个管理一些. net程序集的PowerShell脚本。该脚本是为在。net 2(与PowerShell运行的框架相同版本)上构建的程序集编写的,但现在需要使用。net 4程序集以及。net 2程序集。

由于. net 4支持运行基于旧版本框架构建的应用程序,因此似乎最简单的解决方案是在需要针对. net 4程序集运行PowerShell时,使用。net 4运行时启动PowerShell。

如何使用。net 4运行时运行PowerShell ?


当前回答

请谨慎使用注册表项方法。这些是机器范围的键,强制将所有应用程序迁移到。net 4.0。

如果强制迁移,许多产品不能工作,这是一种测试辅助,而不是一种生产质量机制。Visual Studio 2008和2010,MSBuild, turbotax,以及大量的网站,SharePoint等等都不应该被自动化。

如果您需要使用PowerShell 4.0,这应该在每个应用程序的基础上使用配置文件完成,您应该与PowerShell团队核实准确的建议。这可能会破坏一些现有的PowerShell命令。

其他回答

PowerShell(引擎)在。net 4.0下运行良好。PowerShell(控制台主机和ISE)没有,因为它们是根据旧版本的。net编译的。有一个注册表设置将改变系统范围内加载的。net框架,这将反过来允许PowerShell使用。net 4.0类:

reg add hklm\software\microsoft\.netframework /v OnlyUseLatestCLR /t REG_DWORD /d 1
reg add hklm\software\wow6432node\microsoft\.netframework /v OnlyUseLatestCLR /t REG_DWORD /d 1

要更新ISE以使用。net 4.0,你可以更改配置文件($ phome \powershell_ise.exe.config),使其具有如下块:

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

您可以使用PowerShell API (System.Management.Automation.PowerShell)构建调用PowerShell的。net 4.0应用程序,但是这些步骤将有助于使PowerShell主机在。net 4.0下工作。


当您不再需要注册表项时,请删除它们。这些是机器范围内的键,强制将所有应用程序迁移到。net 4.0,甚至包括使用。net 2和。net 3.5的应用程序


请谨慎使用注册表项方法。这些是机器范围的键,强制将所有应用程序迁移到。net 4.0。

如果强制迁移,许多产品不能工作,这是一种测试辅助,而不是一种生产质量机制。Visual Studio 2008和2010,MSBuild, turbotax,以及大量的网站,SharePoint等等都不应该被自动化。

如果您需要使用PowerShell 4.0,这应该在每个应用程序的基础上使用配置文件完成,您应该与PowerShell团队核实准确的建议。这可能会破坏一些现有的PowerShell命令。

如果你不想修改注册表或app.config文件,另一种方法是创建一个简单的。net 4控制台应用程序,它模仿PowerShell.exe的功能并托管PowerShell ConsoleShell。

参见选项2 -自己托管Windows PowerShell

首先,添加一个对System.Management.Automation和Microsoft. powershell . consolehost程序集的引用,它们可以在%programfiles%\ reference assemblies \Microsoft\WindowsPowerShell\v1.0下面找到

然后使用下面的代码:

using System;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;

namespace PSHostCLRv4
{
    class Program
    {
        static int Main(string[] args)
        {
            var config = RunspaceConfiguration.Create();
                return ConsoleShell.Start(
                config,
                "Windows PowerShell - Hosted on CLR v4\nCopyright (C) 2010 Microsoft Corporation. All rights reserved.",
                "",
                args
            );
        }
    }
}

如果您只需要在。net 4中执行单个命令、脚本块或脚本文件,请尝试使用。net 4中的激活配置文件,使用CLR版本4仅启动单个PowerShell实例。

详情:

http://blog.codeassassin.com/2011/03/23/executing-individual-powershell-commands-using-net-4/

PowerShell模块示例:

https://gist.github.com/882528

只需运行powershell.exe,并将COMPLUS_version环境变量设置为v4.0.30319。 例如,从cmd.exe或。bat-file:

set COMPLUS_version=v4.0.30319
powershell -file c:\scripts\test.ps1