I am executing PowerShell command in C# code. The code adds a email address distribution list in O365. PowerShell is able to add the user to distribution list but it also giving exception too. Why?
using (powershell = PowerShell.Create())
{
command = new PSCommand();
command.AddCommand("Invoke-Command");
string DLGroupName = "UnsubscribersList";
command.AddParameter("ScriptBlock",
System.Management.Automation.ScriptBlock.Create(
"Add-DistributionGroupMember -Identity '" + DLGroupName + "' -Member " + txtEmail.Text + ""));
command.AddParameter("Session", session);
powershell.Commands = command;
powershell.Runspace = runspace;
result = powershell.Invoke();
if (powershell.Streams.Error.Count > 0 || result.Count != 1)
{
throw new Exception("Fail to establish the connection");
}
}
Errors:
powershell.Streams.Error is throwing
Enumeration yielded no results
result.Count is 0
Result will always be 0 .
When you run PowerShell it will execute the script and return the exit code 0 to tell you that PowerShell.exe successfully ran no matter what actually happens inside your script .
If you want results to propagate outside the "PowerShell.exe" instance, you have to either have a command in the script to explicitly exit with a known exit code (exit code 0 typically signals success), or save the result to the HDD/SQL/or somewhere else that can be read.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.