Search code examples
powershellformstextbox

Powershell Textbox Catching Results


Scenario:

I have a form with TEXTBOXA, TEXTBOXB and a BUTTON. BUTTON will add all the groups entered in TEXTBOXB to TEXTBOXA which is working properly. But it does not inform me if any groups failed to be added.

So I would like to add log catching.

All outcomes from the For Loop should be showed in TextboxB. Currently, it will show only that it completed without alerting me of any errors.

Here's the code:

Foreach ($group in $groups)
{
Add-ADGroupMember -Identity $group -Members $loginid.text -credential $admin -Confirm:$false
$Output2.text = "All Groups Added. Please review and confirm."
clear-content $bulkgrouppath

Tried using write-error and write-output but I don;t think I'm using it correctly


Solution

  • You can use a try / catch for error handling, as an example of how it would look with your current implementation:

    foreach ($group in $groups) {
        try {
            Add-ADGroupMember -Identity $group -Members $loginid.text -Credential $admin -Confirm:$false
            $Output2.Text += "'$group' processed successfully.`n"
            Clear-Content $bulkgrouppath
        }
        catch {
            # assign the error message to the TextBoxB
            $Output2.Text += "Failed to process '$group' with error: '$($_.Exception.Message)'.`n" 
            # additionally you can output it to the console for additional troubleshooting
            Write-Error $_
        }
    }