Office 365: 使用Power Shell脚本连接Office Online 365服务的问题

3
我有一台装有Windows Server 2008 R2的机器,它运行的是Power Shell v1.0。我想使用C#和Power Shell连接到MS 365在线服务。我已经安装了Office 365 cmdlets和Microsoft Online Services Sign-In Assistant。(参考:http://onlinehelp.microsoft.com/en-us/office365-enterprises/hh124998.aspx#BKMK_install)。
我的脚本是:
$password = ConvertTo-SecureString "xxxxx" -AsPlainText –Force

$credential = New-Object System.Management.Automation.PsCredential("xxxx@xxxx.onmicrosoft.com",$password)

$cred = Get-Credential -cred $credential

Import-Module MSOnline

Connect-Msolservice -cred $cred

我可以在Power Shell命令窗口成功运行此脚本。但是我在C#应用程序中运行这个脚本遇到了问题。
以下是我的C#代码:
  public void RunScript()
    {
        StringBuilder ss = new StringBuilder();
        ss.AppendLine("$password = ConvertTo-SecureString \"" + pwd + "\" -AsPlainText –Force");
        ss.AppendLine("$credential = New-Object  System.Management.Automation.PsCredential(\"" + userName + "\",$password)");
        ss.AppendLine("$cred = Get-Credential -cred $credential");
        ss.AppendLine("Import-Module MSOnline");
        ss.AppendLine("Connect-Msolservice -cred $cred");

        using (Runspace runspace = RunspaceFactory.CreateRunspace())
        {
            Collection<PSObject> results = null;
            try
            {
                runspace.Open();
                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(ss.toString());

                results = pipeline.Invoke();
            }
            finally
            {
                runspace.Close();
            }                
        }
    }

我遇到了以下异常:

无法识别术语“Connect-Msolservice”作为 cmdlet、函数、脚本文件或可操作的程序名称。请检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。

有什么遗漏吗?

谢谢

2个回答

1
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[] { "MSOnline" });

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

2
谢谢您的评论。我也会尝试您的建议。不过,我已经找到了它无法识别“Connect-Msolservice”命令的原因。原因很简单。我创建了一个控制台应用程序,其平台目标是x86,而我的开发机器是Microsoft Server 2008 64位,我在其中安装了MS Online Service模块(64位)。将平台目标更改为任何CPU即可解决此问题。 - Prakash
嗨,David,我尝试使用以上解决方案,但结果相同(无成功)。顺便说一句,似乎必须从64位进程/应用程序中执行/运行MS Online服务模块(64位)的CMDlet。这是我的经验。如果您有任何想法,请分享。 - Prakash
感谢分享,Prakash。我也遇到了同样的问题。 - ACR
我在我的64位Windows 10机器上遇到了问题,然后在项目属性中,我将构建->平台目标设置为x64,脚本成功导入了模块。 - Auri Rahimzadeh

0
请确保您已安装以下内容:

 1. SharePoint Online Management Shell
 2. Microsoft Online Services Sign-In Assistant version 7.0 or greater version
 3. Windows Azure Active Directory Module

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接