简体   繁体   中英

C# Powershell AddScript not working

! I modified the code in the examples below for easy reading and clarification (so don't mention there is no exception handling etc) !

The Goal:
I'm trying to link a GPO to an ActiveDirectory OU using Powershell in C# (using the System.Management.Automation dll)

The input string (will be used in .AddScript later)

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

The code where the magic should be happening..

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

For those who want to see the singleton

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;
        }
    }
}

The Result

The code executes without any errors in stream or exceptions... However nothing has actually happened. The PowerShell Instance is running on a Windows2008R2

NOTE: I also executed the code in a powershell console on the server, there it is working fine...

UPDATE

Seemed I do had an error in my stream.. guess I missed it somehow, however, here is the exception:

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

Found the solution (Thanks to post: Stack post by 'jamone'):

In order to use a CLR 2.0 mixed mode assembly, you need to modify your App.Config file to include:

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

The key is the useLegacyV2RuntimeActivationPolicy flag. This causes the CLR to use the latest version (4.0) to load your mixed mode assembly. Without this, it will not work.

Note that this only matters for mixed mode (C++/CLI) assemblies. You can load all managed CLR 2 assemblies without specifying this in app.config.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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