繁体   English   中英

C#Powershell AddScript无法正常工作

[英]C# Powershell AddScript not working

我在下面的示例中修改了代码,以方便阅读和阐明(因此请不要提及没有异常处理等)

目标:
我正在尝试使用C#中的Powershell将GPO链接到ActiveDirectory OU(使用System.Management.Automation dll)

输入字符串 (稍后将在.AddScript中使用)

import-module grouppolicy;New-GPLINK -name Workstations -target "OU=Workstations,OU=Computers,OU=TestBuilding,OU=Buildings,OU=Demo,DC=FABRICAM,DC=COM" -LinkEnabled YES -Server MYSERVER.FABRICAM.COM

应该发生魔术的代码。

Integration.PowerShell.Classes.Singleton.Instance.AddScript(script); <== The input string
Integration.PowerShell.Classes.Singleton.Instance.Invoke();

对于那些想看单身人士的人

using System.Management.Automation.Runspaces;
using WindowsPowerShell = System.Management.Automation.PowerShell;

internal class Singleton
{
    private static WindowsPowerShell windowsPowerShellRunspace;
    public static WindowsPowerShell Instance
    {
        get
        {
            if (windowsPowerShellRunspace == null)
            {
                Runspace runSpace = RunspaceFactory.CreateRunspace();
                runSpace.Open();

                windowsPowerShellRunspace = WindowsPowerShell.Create();
                windowsPowerShellRunspace.Runspace = runSpace;
            }

            return windowsPowerShellRunspace;
        }
    }
}

结果

代码执行时没有流或异常的任何错误...但是实际上什么也没有发生。 PowerShell实例在Windows2008R2上运行

注意:我还在服务器上的Powershell控制台中执行了代码,在这里工作正常...

更新

好像我的流中确实有一个错误..猜想我以某种方式错过了它,但是,这是一个例外:

The 'New-GPLINK' command was found in the module 'GroupPolicy', but the module could not be loaded. For more information, run 'Import-Module GroupPolicy'.

找到了解决方案(感谢发布:“ jamone”的堆叠发布 ):

为了使用CLR 2.0混合模式程序集,您需要修改App.Config文件以包括:

<?xml version="1.0"?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

关键是useLegacyV2RuntimeActivationPolicy标志。 这将导致CLR使用最新版本(4.0)来加载您的混合模式程序集。 没有这个,它将无法工作。

请注意,这仅对混合模式(C ++ / CLI)程序集有效。 您可以加载所有托管的CLR 2程序集,而无需在app.config中指定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM