Home > database >  Powershell Beginner Scripting
Powershell Beginner Scripting

Time:11-14

I want to write a script such that if the value is less than ...then color is red, if value = ...then color is yellow and if the value is greater than ...then color is dark magenta. I am just experimenting with powershell.

I am a Data Science student, don't know any powershell scripting, just want to have some fun.

CodePudding user response:

Simple q&d (quick and dirty)...

14, 15 | 
ForEach-Object {
    If ($PSItem -eq 15)
    {Write-Host "$($PSItem) is a match" -ForegroundColor Red}
    Else
    {Write-Warning -Message "$($PSItem) is not yet a match"}
}

# Results
<#
WARNING:  is not yet a match
15 is a match
#>

CodePudding user response:

based on your request, i think below PowerShell Code should work:

$random = Get-Random -Minimum 0 -Maximum 20
if ($random -lt 15) { write-host "Number ist $random" -ForegroundColor Red }

elseif ($random -eq 15) { write-host "Number ist $random" -ForegroundColor Green }

elseif ($random -gt 15) { write-host "Number ist $random" -ForegroundColor DarkMagenta }

CodePudding user response:

Here is another version. My console wasn't allowing DarkMagenta to show, so used Magenta instead, but mostly what you are describing. Not everything in the script is necessary, such as the very first [int], so do some experimenting to see what does, and does not, work.

[int]$InputValue = [int](Read-Host -Prompt "Enter a number")
Write-Host "Value is: [" -NoNewLine
Write-Host "$InputValue" -NoNewLine -ForegroundColor gray -BackgroundColor $(if($InputValue -lt 15){[ConsoleColor]::Red}elseif($InputValue -eq 15){[ConsoleColor]::Yellow}else{[ConsoleColor]::Magenta})
Write-Host "]"
  • Related