我有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)
我的脚本是:
$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#application中运行这个脚本时遇到了问题。
这是我的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();
}
}
}
我得到以下异常:
术语&#39; Connect-Msolservice&#39;不被识别为cmdlet,函数,脚本文件或可操作程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。
有什么遗漏吗?
由于
答案 0 :(得分:1)
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[] { "MSOnline" });
using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
{
// blah
}
答案 1 :(得分: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