简体   繁体   中英

c# remote powershell create AD/Exchange user account and modify

We are trying to set a user's logon script from a remote machine in C#. However, we get the error “The term 'Set-ADUser' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.” Do you have any thoughts on how to resolve this error?

using System;

using System.Security;

using System.Management.Automation;

using System.Management.Automation.Runspaces;



namespace PowershellAdUser

{

    class PowershellAdUser

    {

        static void Main(string[] args)

        {

            string runasUsername = @"login";

            string runasPassword = "pass1234";

            SecureString ssRunasPassword = new SecureString();

            foreach (char x in runasPassword)

                ssRunasPassword.AppendChar(x);

            PSCredential credentials =

                new PSCredential(runasUsername, ssRunasPassword);



            var connInfo = new WSManConnectionInfo(

                new Uri("http://1.2.3.4/PowerShell"),

                "http://schemas.microsoft.com/powershell/Microsoft.Exchange",

                credentials);

            connInfo.AuthenticationMechanism =

                AuthenticationMechanism.Basic;



            var runspace = RunspaceFactory.CreateRunspace(connInfo);

            runspace.Open();

            var pipeline = runspace.CreatePipeline();

            var command = new Command("Set-ADUser");

            command.Parameters.Add("ScriptPath", "logonScript.bat");

            command.Parameters.Add("Identity", "test.com/Users/Test User");

            pipeline.Commands.Add(command);

            var results = pipeline.Invoke();

            runspace.Dispose();

        }

    }

}

We also tried adding

var command = new Command("Import-Module activedirectory");
 pipeline.Commands.Add(command);

after

var pipeline = runspace.CreatePipeline();

This is what we get when we add it

“The term 'Import-Module activedirectory' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.”

After all that didn't work we are trying to pass the connection information and the initial session state at the same time in order to get around the previous 'Import-Module not recognized' error. However, it seems that the function RunspaceFactory.CreateRunspace will either take a WSManConnectionInfo object or a InitialSessionState object, but not both. We also tried to set the initial session state after creating the runspace, but the Runspace's InitialSessionState member appears to be private. Is there any way to initialize a runspace with a WSManConnectionInfo object or a InitialSessionState object simultaneously?

using System;
using System.DirectoryServices;
using System.Security;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            var target = "servername";
            var user = "login";
            user = string.Format("{0}\\{1}", target, user);
            string shell = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
            var targetWsMan = new Uri(string.Format("http://{0}:5985/wsman", target));

            var password = "pass1234";
            var ssPassword = new SecureString();
            foreach (char c in password)
            {
                ssPassword.AppendChar(c);
            }

            var cred = new PSCredential(user, ssPassword);
            var connectionInfo = new WSManConnectionInfo(targetWsMan, shell, cred);

            InitialSessionState init_state = InitialSessionState.CreateDefault();
            init_state.ImportPSModule(new[] { "ActiveDirectory" });
            using (var runSpace = RunspaceFactory.CreateRunspace(connectionInfo))
            {
                runSpace.InitialSessionState = init_state;
                var p = runSpace.CreatePipeline();
                runSpace.Open();
                var command = new Command("Set-ADUser");
                command.Parameters.Add("ScriptPath", "logonScript.bat");
                command.Parameters.Add("Identity", "test.com/Users/Test760 Blah760");
                p.Commands.Add(command);

                var returnValue = p.Invoke();
                foreach (var v in returnValue)
                    Console.WriteLine(v.ToString());
            }


            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}

In addition, we also experimented with using the "dsadd" command instead of the "Set-ADUser" command. If we call "dsadd" without any parameters, it will return its help information. However, if we try to pass any parameters, it does not throw any errors, but it does not appear to execute the command either. Does anyone know how to call the "dsadd" command from the Pipeline object?

using (var runSpace = RunspaceFactory.CreateRunspace(connectionInfo))
{
    runSpace.InitialSessionState = init_state;
    var p = runSpace.CreatePipeline();
    runSpace.Open();

    Command cmd = new Command("dsadd");
    cmd.Parameters.Add("ou", "\"OU=test5,OU=Users,DC=test,DC=com\"");

    var returnValue = p.Invoke();
    foreach (var v in returnValue)
        Console.WriteLine(v.ToString());
}

Additional information: The term 'Set-ADUser' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

        var p = runSpace.CreatePipeline();
        runSpace.Open();
        Command com1 = new Command("Import-Module");
        com1.Parameters.Add("Name", "ActiveDirectory");
        p.Commands.Add(com1);
        Command command = new Command("Set-ADUser");
        command.Parameters.Add("Identity", "tuser19");
        command.Parameters.Add("ScriptPath", "logonScript.bat");
        p.Commands.Add(command);
        var returnValue = p.Invoke();

Try the Import-Module command again but don't mix in the parameter with the command name ie separate the parameters out and add via the Parameters collection:

var command = new Command('Import-Module').Parameters.Add('Name', 'ActiveDirectory');

Also, make sure the ActiveDirectory module is on the remote machine. And if that module only loads into a particular bitness console (32-bit or 64-bit) make sure you're using corresponding remoting endpoint.

Try this code. It worked for me

        InitialSessionState iss = InitialSessionState.CreateDefault();
        iss.ImportPSModule(new String[] { @"<Module name or module path>" });


        using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
        {
        }

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