简体   繁体   English

C#远程PowerShell创建AD / Exchange用户帐户并修改

[英]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#. 我们正在尝试从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. 但是,我们收到错误消息“术语'Set-ADUser'未被识别为cmdlet,函数,脚本文件或可运行程序的名称。 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. “术语“导入模块活动目录”未被识别为cmdlet,函数,脚本文件或可操作程序的名称。 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. 但是,函数RunspaceFactory.CreateRunspace似乎将采用WSManConnectionInfo对象或InitialSessionState对象,但不能同时采用两者。 We also tried to set the initial session state after creating the runspace, but the Runspace's InitialSessionState member appears to be private. 我们还尝试在创建运行空间后设置初始会话状态,但是运行空间的InitialSessionState成员似乎是私有的。 Is there any way to initialize a runspace with a WSManConnectionInfo object or a InitialSessionState object simultaneously? 有什么方法可以同时使用WSManConnectionInfo对象或InitialSessionState对象初始化运行空间?

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. 另外,我们还尝试使用“ dsadd”命令代替“ Set-ADUser”命令。 If we call "dsadd" without any parameters, it will return its help information. 如果我们不带任何参数调用“ dsadd”,它将返回其帮助信息。 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? 有谁知道如何从Pipeline对象调用“ dsadd”命令?

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. 附加信息:术语'Set-ADUser'不被视为cmdlet,函数,脚本文件或可运行程序的名称。 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: 再次尝试使用Import-Module命令,但不要将参数与命令名称混在一起,即将参数分开并通过Parameters集合添加:

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

Also, make sure the ActiveDirectory module is on the remote machine. 另外,请确保ActiveDirectory模块在远程计算机上。 And if that module only loads into a particular bitness console (32-bit or 64-bit) make sure you're using corresponding remoting endpoint. 并且如果该模块仅加载到特定的Bitness控制台(32位或64位)中,请确保您使用的是相应的远程处理端点。

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))
        {
        }

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

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