PowerShell脚本:如何获取选中复选框值并插入邮件内容
Here's a straightforward, scalable way to filter and insert only your checked checkboxes into the email content. Assuming your $CB1 to $CB12 are Windows Forms CheckBox controls (each with a Checked property and a Text property describing the responsibility), follow these steps:
Step 1: Gather all checkbox controls
First, collect all 12 checkboxes into an array to simplify looping through them:
# Collect your checkbox variables into a single array $allCheckboxes = @($CB1, $CB2, $CB3, $CB4, $CB5, $CB6, $CB7, $CB8, $CB9, $CB10, $CB11, $CB12)
Step 2: Filter for checked checkboxes
Next, extract the relevant value (text or custom tag) from only the selected checkboxes:
# Get the display text of all checked checkboxes $selectedResponsibilities = $allCheckboxes | Where-Object { $_.Checked } | ForEach-Object { $_.Text }
If you stored a custom value (like a code or internal term) in the checkbox's Tag property instead of using the visible text, replace $_.Text with $_.Tag.
Step 3: Format for the email
Format the selected items to fit your template—bullet points work well for readability, but you can use plain newlines too:
# Format as bullet points (use "`n" instead of "`n- " for plain line breaks) $responsibilitiesText = if ($selectedResponsibilities.Count -gt 0) { "- " + ($selectedResponsibilities -join "`n- ") } else { "None selected" }
Step 4: Build the final email content
Insert the formatted responsibilities into your existing template:
$emailBody = @" Team, Per ticket $SCTicket, $User is requesting access to GetPaid. Details from RITM ticket $RITMTicket are below: Access Type: $AccessType Roll: $Roll Responsibilities: $responsibilitiesText Thank You "@
Example Output
If $CB2 (text: "Manage Invoices") and $CB5 (text: "Process Refunds") are checked, the responsibilities section will look like:
Responsibilities:
- Manage Invoices
- Process Refunds
This approach keeps your code clean and easy to update—if you add more checkboxes later, just extend the $allCheckboxes array.
内容的提问来源于stack exchange,提问作者sbagnato

