PowerShell中MessageBox意外向变量写入无关数据问题排查
$variable Has Unexpected Data (And How to Fix It) Hey, let's break down what's going on with your PowerShell code. The problem boils down to how PowerShell handles function output—it doesn't just return what you specify with return; it returns all un-suppressed output generated in the function.
The Root Cause
Your ShowMessageBox function calls [Windows.Forms.MessageBox]::Show(), which returns a [System.Windows.Forms.DialogResult] enum value (for example, clicking "OK" returns OK, which maps to the number 1). Even though you have return $null in ShowMessageBox, you never captured or suppressed that enum value from the Show() method.
When MyFunction calls ShowMessageBox, that enum value gets passed up as output from ShowMessageBox, and then combined with the "Somevalue" you explicitly return from MyFunction. So $variable ends up being an array containing both the enum value and your intended string—hence the unexpected data.
Fixes You Can Use
There are two simple ways to fix this:
1. Suppress Output from ShowMessageBox in MyFunction
Capture the output of ShowMessageBox with $null (so it doesn't get passed up) or pipe it to Out-Null:
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") Function MyFunction { # Capture the MessageBox result to $null to suppress it $null = ShowMessageBox "Hello World" "Test" return "Somevalue" } Function ShowMessageBox { param ( [string] $message, [string] $title ) [Windows.Forms.MessageBox]::Show("$message", "$title", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information) return $null } $variable = MyFunction Write-Host "The value of my variable is: $variable."
2. Fix the ShowMessageBox Function Directly
Modify ShowMessageBox to capture the Show() method's return value internally, so it never leaves the function:
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") Function MyFunction { ShowMessageBox "Hello World" "Test" return "Somevalue" } Function ShowMessageBox { param ( [string] $message, [string] $title ) # Capture the result locally to prevent it from being output $null = [Windows.Forms.MessageBox]::Show("$message", "$title", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information) return $null } $variable = MyFunction Write-Host "The value of my variable is: $variable."
Verify the Fix
After making either change, $variable will only hold "Somevalue" (a string, not an array). You can confirm this by running $variable.GetType()—it should return System.String instead of an array type.
内容的提问来源于stack exchange,提问作者Matthias

