我試圖連接到Office 365組,並使用PowerShell通過C#項目列出組的成員資格。使用PowerShell讀取C#中的Office 365組成員
From this article,我已經決定我需要使用命令是
Get-UnifiedGroupLinks –Identity groupalias –LinkType Members
這裏是我當前的代碼:
string connectionUri = "https://outlook.office365.com/powershell-liveid/";
SecureString secpassword = new SecureString();
foreach (char c in Password)
{
secpassword.AppendChar(c);
}
PSCredential credential = new PSCredential(UserName, secpassword);
Runspace runspace = RunspaceFactory.CreateRunspace();
PSObject SessionHolder = null;
using (PowerShell powershell = PowerShell.Create())
{
PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri(connectionUri));
command.AddParameter("Credential", credential);
command.AddParameter("Authentication", "Basic");
powershell.Commands = command;
runspace.Open();
powershell.Runspace = runspace;
Collection<System.Management.Automation.PSObject> result = powershell.Invoke();
if (powershell.Streams.Error.Count > 0 || result.Count != 1)
{
throw new Exception("Fail to establish the connection");
}
else
SessionHolder = result[0];
}
using (PowerShell powershell = PowerShell.Create())
{
PSCommand command = new PSCommand();
// –Identity groupalias –LinkType Members
command = new PSCommand();
command.AddCommand("Invoke-Command");
command.AddParameter("ScriptBlock", System.Management.Automation.ScriptBlock.Create("Get-UnifiedGroupLinks"));
command.AddParameter("Session", SessionHolder);
command.AddParameter("Identity", groupAddress);
command.AddParameter("LinkType", "Members");
powershell.Commands = command;
powershell.Runspace = runspace;
Collection<PSObject> PSOutput = powershell.Invoke();
// loop through each output object item
foreach (PSObject outputItem in PSOutput)
{
}
}
上面使用的變量,未顯示的聲明: 「用戶名」, 「Password」,「groupAddress」
我能夠建立與服務的連接,但是當我嘗試獲取組成員時我收到錯誤「找不到與參數名'身份'相匹配的參數」
我不知道如何繼續解決我的代碼。我已經在Identity參數中嘗試了組電子郵件,羣組別名和羣組顯示名稱。也許我還有其他錯誤?
我使用下面庫在Visual Studio 2017年在Windows 10的機器上:
using System.Management.Automation;
using System.Management.Automation.Runspaces;
我再次檢查變量沒有什麼特別的。我甚至嘗試將電子郵件地址直接放入命令中。不幸的是,同樣的錯誤發生。 – MrMatt
對不起,它的意思是它不承認那個標誌「身份」,如果你添加「-Identity」而不是「身份」,該怎麼辦? – Alex
嗨亞歷克斯,我確實嘗試了'-Identity',它似乎沒有什麼區別,但我找到了一個可能的解決方案。在查看組成員之前,我添加了以下代碼,並開始工作。
PSCommand ImportSession = new PSCommand(); ImportSession.AddCommand("Import-PSSession"); ImportSession.AddParameter("Session", SessionHolder); powershell.Commands = ImportSession; powershell.Invoke();
– MrMatt