Am Ba
Am Ba

Reputation: 65

Powershell if-else

I want to write a powershell code like when you type Laskopia | LevTest | Drift | Pretest, then it will check that it is the correct and return it is correct and if it is not correct return that it is wrong

$Miljö = Read-Host "Enter Laskopia | LevTest | Drift | Pretest"

If ($Miljö -eq "Laskopia") { $Miljö = "Laskopia" }
If ($Miljö -eq "Levtest") { $Miljö = "Levtest" }
If ($Miljö -eq "Drift") { $Miljö = "Drift" }
If ($Miljö -eq "Pretest") { $Miljö = "Pretest" }
Write-Host "Miljön is $Miljö" -ForegroundColor Green 

else
Write-Host "Miljön finns inte" -ForegroundColor Red

Upvotes: 2

Views: 1961

Answers (4)

Maximilian Burszley
Maximilian Burszley

Reputation: 19644

An alternative method to the other answers is using a validation attribute:

[ValidateSet('Laskopia','LevTest','Drift','Pretest','Default')]
[String]$Miljö = 'Default'

Try
{
    $Miljö = Read-Host 'Enter Laskopia | LevTest | Drift | Pretest'
    Write-Host "Miljön is $Miljö" -ForegroundColor 'Green'
}
Catch
{
    Write-Host 'Miljön finns inte' -ForegroundColor 'Red'
}

Upvotes: 1

Reza Aghaei
Reza Aghaei

Reputation: 125197

To avoid repeating things, it's better to keep those valid values in an array and use such script:

$ValidValues = @("Some value", "Another", "Another one")
$Value = Read-Host "Enter one of following values: $($ValidValues -join " | ")"
if($ValidValues -icontains $Value){
    Write-Host "Value = $Value" -ForegroundColor Green
} else {
    Write-Host "$Value is not a value value." -ForegroundColor Red
}

Upvotes: 1

Bacon Bits
Bacon Bits

Reputation: 32145

if ($Miljö -in ('Laskopia','LevTest','Drift','Pretest')) {
    Write-Host "Miljön is $Miljö" -ForegroundColor Green 
}
else {
    Write-Host "Miljön finns inte" -ForegroundColor Red
}

To force correct user input from a fixed selection, it's usually better to do something like:

do {
    $Miljö = Read-Host "Enter Laskopia | LevTest | Drift | Pretest"
while ($Miljö -notin ('Laskopia','LevTest','Drift','Pretest'));

Upvotes: 3

faceman
faceman

Reputation: 1328

You could also use a switch statement for that:

$Miljö = Read-Host "Enter Laskopia | LevTest | Drift | Pretest"
switch ($Miljö) 
{ 
    {$_ -in "Laskopia", "Levtest", "Drift", "Pretest"} { Write-Host "Miljön is $Miljö" -ForegroundColor Green }
    default { Write-Host "Miljön finns inte" -ForegroundColor Red }
}

You need Powershell 3.0 for the -in Operator

Upvotes: 4

Related Questions