1

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.

foobar
  • 87
  • 6

1 Answers1

2

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • I really wanna learn c# :(. How did you find out if the cmdlet was a non-terminating error? Is there a simple way? – Abraham Zinala Nov 03 '21 at 03:43
  • 1
    @AbrahamZinala, generally speaking, _most_ cmdlet errors are non-terminating. You can easily provoke a _terminating_ one with a _syntax error_, by passing a non-existent parameter name. If you're unsure in a given situation, use the following trick (using a `Get-Item` call as an example): `'!' + (Get-Item nosuch)`: If `!` still prints, the error is non-terminating. – mklement0 Nov 03 '21 at 15:24