我有Windows Server 2008 R2计算机,它具有Power Shell v1.0。我想使用Power Shell与C#连接到MS 365在线服务。我已经安装了Office 365 cmdlet和Microsoft Online Services登录助手。 (参考文献:http://onlinehelp.microsoft.com/en-us/office365-enterprises/hh124998.aspx#BKMK_install)Office 365:使用Power Shell脚本连接到Office Online 365服务
我的脚本是:
$password = ConvertTo-SecureString "xxxxx" -AsPlainText –Force
$credential = New-Object System.Management.Automation.PsCredential("[email protected]",$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();
}
}
}
我得到以下异常:
'连接-Msolservice' 一词未被识别为cmdlet,函数的名称,脚本文件,或可操作程序。检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。
有什么遗漏吗?
感谢
的评论以及感谢。我也会尝试你的建议。但是,我发现它不能识别“Connect-Msolservice”命令的原因。原因很简单。我创建了一个控制台应用程序,其Platform目标是x86,而我的开发机器是Microsoft Server 2008 64bit,我已经安装了MS Online Service模块(64位)。通过将平台目标更改为任何CPU来解决问题。 – Prakash 2012-04-17 17:41:27
嗨大卫,我试着用上述解决方案,但结果相同(没有成功)。 顺便说一句。 MS Online服务模块(64位)的cmdlet似乎必须从64位进程/应用程序执行/运行。这是我所经历的。如果你对此有任何想法,请分享。 – Prakash 2012-04-18 11:26:57
感谢分享,普拉卡什。我遇到了同样的问题。 – ACR 2016-10-13 14:51:25