Hello,
I'm working on creating a C# routine in Visual Studio. Using the System.Management.Automation and System.Management.Automation.Runspaces namespaces, I'm attempting to run Powershell commands to retrieve and set information in Office 365.
I found an Article that shows the commands in Powershell, but need help converting them into C#
Here is the code I have so far. I have defined 3 variables "UserName", "Password", "groupAddress" that aren't shown for security reasons.
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(); 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) { } }
I can establish the connection in the first PowerShell, but once I get to the second one, I get an error saying "A parameter cannot be found that matches parameter name 'Identity'".
I know that exists because the Powershell command is
Get-UnifiedGroupLinks –Identity groupalias –LinkType Members
Perhaps I'm not using it correctly? or maybe there is a better method I should be using. My goal is to read the users in the group so I can add missing members, or remove members via my script.
I appreciate any guidance you might have.
Thanks!