How can I catch the Powershell exceptions AccessDeniedException
and GroupExistsException
within my C# program for the cmdlet New-LocalGroup
try
{
PowerShell ps = PowerShell.Create();
ps.AddCommand("New-LocalGroup");
ps.AddParameter("Name", groupName);
ps.AddParameter("Description", description);
ps.Invoke();
}
catch (Exception ex)
{
if (ex is ?)
throw ex;
}
So far, I have this link from Microsoft documentation here.
CodePudding user response:
What the New-LocalGroup
cmdlet emits are non-terminating PowerShell errors (unless you use invalid syntax), which do not translate into .NET exceptions.
Instead, they are written to PowerShell's error output stream, which you can examine via ps.Streams.Error
See this answer for more information.