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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I really wanna learn c# :(. How did you find out if the cmdlet was a non-terminating error? Is there a simple way?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.