Search code examples
powershellscriptingconcatenationstring-concatenationwrite-host

How to concatenate 2 Write-Output on the same line?


I wrote a script that can return you if a software is installed or not.

I would like to give it a bit of colors but I don't know how to concatenate 2 Write-Output on the same line as -NoNewline only works for Write-Host... which in this case I cannot use:

# The function we use to give color

function Positive {
    process { Write-Host $_ -ForegroundColor Green }
    }

function Negative {
    process { Write-Host $_ -ForegroundColor Red }
    }

# Is the software installed?
# '0' = NO, is not installed
# '1' = YES, is installed

$Check = '1'

function Check_Installation($Check){
    if ($Check -eq '0') {return $response =  "No, is not installed" | Negative}
    elseif ($Check -eq '1') {return $response =  "Yes, is installed" | Positive}
    }

$First_Phrase =  "Let's check if the software is installed: "

Write-Output "$First_Phrase", "$response"

Check_Installation($Check)

enter image description here

I know I can concatenate with

[string]::Concat("$First_Phrase", "$response")

but is not working.


Solution

  • This works in console only as changing the foreground colour in ISE changes it for every line:

    # The function we use to give color
    
    function Set-Output {
        param ($colour, $str1, $str2)
    
        $t = $host.ui.RawUI.ForegroundColor
        $host.ui.RawUI.ForegroundColor = "$colour"
    
        $text = "$str1 $str2"
    
        Write-Output "$text"
    
        $host.ui.RawUI.ForegroundColor = $t
    
    }
    
    # Is the software installed?
    # '0' = NO, is not installed
    # '1' = YES, is installed
    
    $Check = '1'
    
    $First_Phrase =  "Let's check if the software is installed: "
    
    Switch ($check) {
        ( 0 ) {Set-Output -colour RED -str1 $First_Phrase -str2 "No, is not installed" }
        ( 1 ) {Set-Output -colour GREEN -str1 $First_Phrase -str2  "Yes, is installed" }
    }
    
    Check_Installation($Check)
    

    All that it is doing is concatenating the two strings and changing the foreground colour.

    enter image description here