gpt4 book ai didi

c# - 办公室 365 : Connecting to Office Online 365 service using Power Shell Script issue

转载 作者:行者123 更新时间:2023-11-30 18:00:21 24 4
gpt4 key购买 nike

我有 Windows Server 2008 R2 机器,它有 Power Shell v1.0。我想使用带有 C# 的 Power Shell 连接到 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# 应用程序中运行此脚本时遇到问题。

这是我的 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、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。

有什么遗漏吗?

谢谢

最佳答案

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

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

关于c# - 办公室 365 : Connecting to Office Online 365 service using Power Shell Script issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10169140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com