Ошибка при запуске командлетов AD в powershell из C#

Я попытался выполнить командлеты AD в powershell, используя С#, с того же компьютера. Это прекрасно работает.

static void Main(string[] args)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            iss.ImportPSModule(new string[] { "activedirectory" });
            Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss);
            myRunSpace.Open();

            Pipeline pipeLine = myRunSpace.CreatePipeline();
            Command myCommand = new Command("Get-ADUser");
            myCommand.Parameters.Add("Filter", "sAMAccountName -eq 'user1'");
            //myCommand.Parameters.Add("IncludeDeletedObjects");

            pipeLine.Commands.Add(myCommand);

            //Command restoreCommand = new Command("Restore-ADObject");
            //pipeLine.Commands.Add(restoreCommand);

            Console.WriteLine("Before Invoke");
            Collection<PSObject> commandResults = pipeLine.Invoke();
            Console.WriteLine("After Invoke");

            foreach (PSObject cmdlet in commandResults)
            {
                //Console.WriteLine("Inside foreach");  
                string cmdletName = cmdlet.BaseObject.ToString();
                System.Diagnostics.Debug.Print(cmdletName);
                Console.WriteLine(cmdletName);
            }

            Console.ReadLine();
        }

Но при попытке запустить ту же команду удаленно с помощью команды вызова выдает ошибку The term 'Get-ADUser' is not recognized as the name of a cmdlet, function, script file, or operable program.

Ниже приведена моя программа:

static void Main(string[] args)
    {

        string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
        string userName = "Domain\\Administrator";
        string password = "Password";
        SecureString securePassword = new SecureString();

        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }
        PSCredential credential = new PSCredential(userName, securePassword);
        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machinename", 5985, "/wsman", shellUri, credential);
        using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
        {

            runspace.Open();
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = runspace;
                PSCommand new1 = new PSCommand();
                new1.AddCommand("Get-ADUser");
                new1.AddParameter("identity", "CN=user1,DC=example,DC=com");
                powershell.Commands = new1;
                Collection<PSObject> results = powershell.Invoke();
                foreach (PSObject obj in results)
                {
                 PSMemberInfoCollection<PSPropertyInfo> propInfos = obj.Properties;
                 Console.WriteLine("********************");
                 foreach (PSPropertyInfo propInfo in propInfos)
                 {
                     string propInfoValue = (propInfo.Value == null) ? "" : propInfo.Value.ToString();
                     Console.WriteLine("{0} --> {1}", propInfo.Name, propInfoValue);
                 }


             }

            }
        }
     }
  1. Как я могу удаленно вызывать командлеты AD?
  2. Есть ли способ удаленно вызывать команды, используя InitialSessionState, а не WSManConnectionInfo .
  3. Если я использую invoke-command -computername $DC -ScriptBlock {Remove-ADUser -identity "user1"} -credential $cred - я получаю ошибку The term 'Remove-ADUser' is not recognized as the name of a cmdlet, function, script file, or operable program.

Но можно использовать команду Remove-ADUser -identity "user1" -server $DC -credential $cred. Как напрямую выполнить команду AD в powershell из клиента C#?


person cmm user    schedule 23.11.2013    source источник
comment
Вы убедились, что модуль ActiveDirectory установлен на вашем целевом компьютере?   -  person Joseph Alcorn    schedule 23.11.2013


Ответы (1)


Вам необходимо импортировать модуль ActiveDirectory в удаленное пространство выполнения перед выполнением команды AD, например:

powershell.Commands.AddCommand("Import-Module").AddArgument("ActiveDirectory");
powershell.Invoke();
powershell.Commands.Clear();
person Keith Hill    schedule 23.11.2013