Search code examples
c#powershellvisual-studio-2012active-directoryrunspace

How do I Run PowerShell command in windows form application?


I am currently trying to implement the below ps command in my c# forms app.

Im using Quest Powershell cmdlet

    Add-PSSnapin -Name Quest.ActiveRoles.ADManagement
    get-qadmemberof -identity 'ssc\rpimentel' | Where-Object {$_.Name -ne "Domain Users"} | Add-QADGroupmember -member 'ktest'

The powershell command i have works, but i cannot get the below code to work. Command not found Exception is thrown "The term Get-QADMemberOf is not recognized as the name of a cmdlet.

            PowerShell ps = PowerShell.Create();

            PSCommand cmd1 = new PSCommand();
            cmd1.AddCommand("Import-Module");
            cmd1.AddParameter("activedirectory");
            cmd1.AddCommand("Add-PSSnapin");
            cmd1.AddParameter("Name", "Quest.ActiveRoles.ADManagement");
            cmd1.AddCommand("Get-QADMemberOf");
            cmd1.AddParameter("identity", "rpimentel");
            cmd1.AddCommand("where-object");
            ScriptBlock filter = ScriptBlock.Create("$_.Name -ne 'Domain Users'");
            cmd1.AddParameter("FilterScript", filter);
            cmd1.AddCommand("Add-QADGroupmember");
            cmd1.AddParameter("Member", "ktest");

            ps.Commands = cmd1;
            ps.Invoke();

Solution

  • As per my comment maybe try the following:

            PowerShell ps = PowerShell.Create();
    
            PSCommand cmd1 = new PSCommand();
            cmd1.AddCommand("Import-Module");
            cmd1.AddParameter("activedirectory");
            ps.Commands = cmd1;
            ps.Invoke();
    
            cmd1.AddCommand("Add-PSSnapin");
            cmd1.AddParameter("Name", "Quest.ActiveRoles.ADManagement");
            ps.Commands = cmd1;
            ps.Invoke();
    
            cmd1.AddCommand("Get-QADMemberOf");
            cmd1.AddParameter("identity", "rpimentel");
            cmd1.AddCommand("where-object");
            ScriptBlock filter = ScriptBlock.Create("$_.Name -ne 'Domain Users'");
            cmd1.AddParameter("FilterScript", filter);
            cmd1.AddCommand("Add-QADGroupmember");
            cmd1.AddParameter("Member", "ktest");
            ps.Commands = cmd1;
            ps.Invoke();