【问题标题】:Running PowerShell commands from C#从 C# 运行 PowerShell 命令
【发布时间】:2016-05-18 01:01:18
【问题描述】:

我有 powershell 脚本,它可以连接到在线交流并执行创建共享邮箱、日历、添加许可证等任务。

问题是,当我从 C# 类运行这些命令时,我得到了错误。

这是我的连接:

 string schemaURI = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
        Uri connectTo = new Uri("https://outlook.office365.com/powershell-liveid/");

        var securePassword = new SecureString();

        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }

        this.credential = new PSCredential(login, securePassword);
        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(connectTo, schemaURI, credential);
        connectionInfo.MaximumConnectionRedirectionCount = 5;
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;


            this.remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
            this.remoteRunspace.Open();

这是我运行良好的 PowerShell:

  PowerShell powershell = PowerShell.Create();
                powershell.Runspace = this.remoteRunspace;
                PSCommand command = new PSCommand();

                command.AddCommand("new-mailbox");
                command.AddParameter("Name", mailboxName);
                command.AddParameter("Shared");
                command.AddParameter("PrimarySmtpAddress", formatedMailboxName);
                powershell.Commands = command;

                powershell.Invoke();

这是无法正常工作的代码:

 PowerShell powershell = PowerShell.Create();
                powershell.Runspace = this.remoteRunspace;
                PSCommand command = new PSCommand();
                command.AddCommand("Connect-MsolService");
                command.AddCommand("Import-Module MSOnline");
                command.AddParameter("Credential", this.credential);
                command.AddCommand("Set-MsolUser");
                command.AddParameter("UserPrincipalName", userLogin);
                command.AddParameter("UsageLocation", "SE");

我得到的错误如下:

附加信息:“Import-Module MSOnline”一词未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。

我尝试了各种方法,例如复制粘贴 dll 并将活动解决方案平台 CPU 更改为 64 位,但没有任何帮助。

【问题讨论】:

  • Import-Module 是命令名称 MSOnline 是参数。
  • 附加信息:“Import-Module”一词未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,如果包含路径,请验证路径是否正确,然后重试。

标签: c# visual-studio powershell exchange-server office365


【解决方案1】:

可能很愚蠢,但您尝试过以下方法吗?

command.AddCommand("Import-Module 'MSOnline'");

我遇到了类似的问题,但使用的是 skypeforbusiness 模块。当我添加''时工作。

可以在powershell ise中执行Import-Module MSOnline命令吗?

【讨论】:

    【解决方案2】:

    我找到了问题的解决方案here

    【讨论】:

      【解决方案3】:

      download scriptCreateNewMail[download script assign linces]1 类程序:Cmdlet {

          string AdminUserName = "";
          string AdminPassword = "";
          string MailBoxUserAliasName = "red";
          string MailBoxUserName = "redyellow";
          string MailBoxUserFirstName = "red";
          string MailBoxUserLastName = "yellow";
          string MailBoxUserDisplayName = "red yellow";
          string MailBoxUserMicrosoftOnlineServicesID = "red.yellow@vt0365dev.onmicrosoft.com";
          string MailBoxUserPassword = "P@ssw0rd";
          string MailBoxUserUsageLocation = "IN"; // Set Country of the User
          string MailBoxUserAddLicenses = ""; // Assign Licenses
      
          /// <summary>
          ///  Connect to the PowerShell 
          ///  1. Connect to 365 office with Admin login
          ///  2  Create New MailBox
          ///  3  Set the Country to the user
          ///  3  Set the Country to the user
          ///  4. Assign Licences  to account user
          /// </summary>
          /// <param name="commandFileName"> command file name</param>
          /// <param name="ErrorMessage"> error message</param>
          /// <returns> true or false </returns>
          public bool ConnectPowerShell(string commandFileName, ref string ErrorMessage)
          {
              Program Object_Pro = new Program();
              String input;
              Runspace runspace = null;
              Pipeline pipeline = null;
              PipelineStateInfo info = null;
      
              try
              {
                  if (File.Exists(commandFileName))
                  {
                      using (StreamReader sr = File.OpenText(commandFileName))
                      {
                          runspace = RunspaceFactory.CreateRunspace();
                          pipeline = runspace.CreatePipeline();
      
                          runspace.Open();
      
                          while ((input = sr.ReadLine()) != null)
                          {
                              //Replace the Peramter Value to original value
                              input = input.Replace("@@username", Object_Pro.AdminUserName);
                              input = input.Replace("@@password", Object_Pro.AdminPassword);
                              input = input.Replace("@@Alias", Object_Pro.MailBoxUserAliasName.ToLower());
                              input = input.Replace("@@Name", Object_Pro.MailBoxUserName.ToLower());
                              input = input.Replace("@@FirstName", Object_Pro.MailBoxUserFirstName.ToLower());
                              input = input.Replace("@@LastName", Object_Pro.MailBoxUserLastName.ToLower());
                              input = input.Replace("@@DisplayName", Object_Pro.MailBoxUserDisplayName.ToLower());
                              input = input.Replace("@@MicrosoftOnlineServicesID", Object_Pro.MailBoxUserMicrosoftOnlineServicesID.ToLower());
                              input = input.Replace("@@UPassword", Object_Pro.MailBoxUserPassword);
                              input = input.Replace("@@UsageLocation", Object_Pro.MailBoxUserUsageLocation);
                              input = input.Replace("@@AddLicenses", Object_Pro.MailBoxUserAddLicenses);
      
                              pipeline.Commands.AddScript(input);
                          }
      
                          pipeline.Commands.Add("Out-String");
                          Collection<PSObject> results = pipeline.Invoke();
                          runspace.Close();
                      }
      
                      info = pipeline.PipelineStateInfo;
      
                      if (info.State != PipelineState.Completed)
                      {
                          ErrorMessage = info.Reason.ToString();
                          return false;
                      }
                      else
                      {
                          ErrorMessage = "";
                          return true;
                      }
                  }
                  else
                  {
                      ErrorMessage = "File not found";
                      return false;
                  }
              }
              catch (Exception ex)
              {
                  ErrorMessage = ex.Message;
                  return false;
              }
          }
      
          static void Main(string[] args)
          {
              string StrErrorMessage = string.Empty;
              bool ConnectResult;
      
              // Create Object of Program class
              Program ObjProgram = new Program();
      
              // File Name Of the PowerShell Command
              string fileName = @"E:\scriptCreateNewMail.txt";
              string ScriptFileNameForSetLocation = @"E:\scriptUserlocationset.txt";
      
              try
              {
                  ConnectResult = ObjProgram.ConnectPowerShell(fileName, ref StrErrorMessage);
                  if (ConnectResult)
                  {
                      ConnectResult = ObjProgram.ConnectPowerShell(ScriptFileNameForSetLocation, ref StrErrorMessage);
                      if (ConnectResult)
                      {
                          Console.WriteLine("task completed");
                      }
                      else
                      {
                          Console.WriteLine(StrErrorMessage);
                      }
                  }
                  else
                  {
                      Console.WriteLine(StrErrorMessage);
                  }
              }
              catch (ExitException ex)
              {
                  Console.WriteLine(ex.Message);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-02
        • 2018-03-14
        • 2023-04-06
        相关资源
        最近更新 更多