首页 > 解决方案 > Powershell MessageBox 将不需要的数据添加到我的变量中

问题描述

考虑这个 Powershell 代码:

[System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)

Function MyFunction {
    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."

我将变量 $variable 分配给函数“MyFunction”返回的变量,即字符串“Somevalue”。

在返回这个字符串之前,我会显示一个消息框。

然后我打印 $variable 的值。这应该是“Somevalue”,但我得到了这个结果:

好的一些值

这个额外的“OK”是从哪里来的?

标签: powershell

解决方案


在 PowerShell 中,您未分配或通过管道传输到 cmdlet 的所有内容都会被放入管道。return 语句只退出一个函数,在你的情况下你可以省略它。

Show要解决您的问题,请将方法的结果通过管道传输到Out-Null

[System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)

Function MyFunction {
    ShowMessageBox "Hello World" "Test"
    "Somevalue"
}

Function ShowMessageBox {
    param (
        [string] $message,
        [string] $title
    )
    [Windows.Forms.MessageBox]::Show("$message", "$title", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information) | Out-Null
}


$variable = MyFunction
Write-Host "The value of my variable is: $variable."

推荐阅读