Search code examples
powershellcompareobject

Add new lines in variable displayed via PowerShell message box


I have made a simple PowerShell message box to display the names of missing files. I call them with a variable. When I echo the variable in ISE it displays each on a separate line, however when displayed in the message box it comes out as a string separated by spaces. I haven't had any luck replacing the spaces with `n but perhaps I did it wrong.

Any one have any ideas?

Current code:

$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{
}

Output in ISE looks like:

File1

File2

File3

Output in message box looks like:

File1 File2 File3


Solution

  • $missing is a list of strings, so when you Echo them the console takes care of formatting them on multiple lines.

    Achieving the same in a MessageBox requires that you join the strings using newline characters (ASCII 10).

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

    This line uses the String.Join Method (System) to concatenate the file names into a single string, joined by newline characters. [Convert]::ToChar(10) is essentially \n but using that results in that literal string being used instead of the newline character. We're just converting the ASCII code 10 to a character (and then a string) and using it to join the file names.

    Here's the updated script:

    $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
    
    }
    

    Here is the result:

    MessageBox