Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-Host with multiple colors

Tags:

powershell

In one of my powershell functions, I want to gather input from the user, but first I need to give some instructions. I'd like to print a line or two in the console with different colors.

function myFunction(){
    param(
        [string]$directions = $(read-host "Please answer the questions according to your opinion`nYour answers must be Star Wars-based." -foregroundcolor "Magenta"),
        [string]$robot = $(read-host "What is your favourite robot" -foregroundcolor "Yellow"),
        [string]$spaceship = $(read-host "What is your favourite spaceship" -foregroundcolor "Green")
    )
    write-host "Favourite Robot = " + $robot
    write-host "Favourite Spaceship = " + $spaceship
}
#call the function
myFunction

In the function above I have a newline to keep the directions on separate levels, but I want the first line of this text to be one colour and the second line to be another colour.

Also, -foregroundcolor doesn't work here - it just prints literally.

I can't put a write-host before the param statement or I would put the directions there (I know how to do this with multiple colours).

like image 996
bgmCoder Avatar asked Jul 24 '26 10:07

bgmCoder


1 Answers

You seem to be struggling a little with the instructions in the comments so here... Unsure why you want a read host for instructions but that's cool.

function myFunction(){
    param(
        [string]$directions = $(Write-Host "Please answer the questions according to your opinion`nYour answers must be Star Wars-based.: " -ForegroundColor Magenta -NoNewline; Read-Host),
        [string]$robot = $(Write-Host "What is your favourite robot: " -ForegroundColor Yellow -NoNewline; Read-Host),
        [string]$spaceship = $(Write-Host "What is your favourite spaceship: " -ForegroundColor Green -NoNewline; Read-Host)
    )
    write-host "Favourite Robot = "$robot
    write-host "Favourite Spaceship = "$spaceship
}
like image 153
Drew Avatar answered Jul 28 '26 04:07

Drew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!