! 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'.