首页 > 解决方案 > 在通过 PowerShell 消息框显示的变量中添加新行

问题描述

我制作了一个简单的 PowerShell 消息框来显示丢失文件的名称。我用变量调用它们。当我在 ISE 中回显变量时,它会在单独的行中显示每个变量,但是当显示在消息框中时,它会显示为由空格分隔的字符串。我没有运气用 `n 替换空格,但也许我做错了。

有人有想法么?

当前代码:

$missing = Compare-Object $capture.BaseName $output.BaseName | Select-Object -ExpandProperty InputObject
If($missing -ne $null){
Write-Host 'Here are the missing file(s):'
    echo $missing

#send pop up alert
$ButtonType = [System.Windows.MessageBoxButton]::OK
$MessageboxTitle = “Please Process Files”
$Messageboxbody = “
The following are missing:

$missing”
$MessageIcon = [System.Windows.MessageBoxImage]::Warning
[System.Windows.MessageBox]::Show($Messageboxbody,$MessageboxTitle,$ButtonType,$messageicon)
}Else{
}

ISE 中的输出如下所示:

文件 1

文件2

文件 3

消息框中的输出如下所示:

文件 1 文件 2 文件 3

标签: powershellcompareobject

解决方案


$missing是一个字符串列表,因此当您使用Echo它们时,控制台会负责将它们格式化为多行。

在 a 中实现相同MessageBox要求您使用换行符 (ASCII 10) 连接字符串。

$([String]::Join(([Convert]::ToChar(10)).ToString(), $missing)

此行使用String.Join 方法(系统)将文件名连接成单个字符串,并由换行符连接。[Convert]::ToChar(10)本质上是\n,但使用它会导致使用该文字字符串而不是换行符。我们只是将 ASCII 代码 10 转换为一个字符(然后是一个字符串)并使用它来连接文件名。

这是更新的脚本:

$missing = Compare-Object $capture.BaseName $output.BaseName | Select-Object -ExpandProperty InputObject

If($missing -ne $null){
    Write-Host 'Here are the missing file(s):'
        Echo $missing

    # Send pop up alert

    $missingWithNewlines = $([String]::Join(([Convert]::ToChar(10)).ToString(), $missing))

    $ButtonType = [System.Windows.MessageBoxButton]::OK

    $MessageboxTitle = “Please Process Files”

    $Messageboxbody = “
The following are missing:

$missingWithNewlines”

    $MessageIcon = [System.Windows.MessageBoxImage]::Warning

    [System.Windows.MessageBox]::Show($Messageboxbody,$MessageboxTitle,$ButtonType,$messageicon)

}Else{

    # Nothing missing

}

结果如下:

消息框


推荐阅读