Reputation: 25
I have written the following PowerShell script below:
if ($Animal -eq "Chicken") {
if ($Food -eq "Egg") {
Write-Host "This chicken eats egg"
} ElseIf ($Food -eq "Soup") {
Write-Host "This chicken eats soup"
} ElseIf ($Animal -eq "Cow") {
if ($Food -eq "Egg") {
Write-Host "This cow eats egg"
} ElseIf ($Food -eq "Soup") {
Write-Host "This cow eats soup"
} ElseIf ($Animal -eq "Zebra") {
if ($Food -eq "Egg") {
Write-Host "This zebra eats egg"
} ElseIf ($Food -eq "Soup") {
Write-Host "This zebra eats soup"
The script works for the Chicken and the Cow but does not register the zebra portion of the code. I am not sure of what I am doing wrong as there are no errors being returned. Can someone please provide some guidance?
Upvotes: 2
Views: 383
Reputation: 10811
You are missing the }
after your ElseIf
s.
Corrected code:
if ($Animal -eq "Chicken") {
if ($Food -eq "Egg") {
Write-Host "This chicken eats egg"
} ElseIf ($Food -eq "Soup") {
Write-Host "This chicken eats soup"
}
} ElseIf ($Animal -eq "Cow") {
if ($Food -eq "Egg") {
Write-Host "This cow eats egg"
} ElseIf ($Food -eq "Soup") {
Write-Host "This cow eats soup"
}
} ElseIf ($Animal -eq "Zebra") {
if ($Food -eq "Egg") {
Write-Host "This zebra eats egg"
} ElseIf ($Food -eq "Soup") {
Write-Host "This zebra eats soup"
}
}
That said, as @MathiasR.Jessen pointed out, this can be simplified using variable expansion:
Write-Host "This $($Animal.ToLower()) eats $($Food.ToLower())"
See About Quoting Rules for more info.
Upvotes: 2
Reputation: 2405
Whilst I fully agree with Doug's answer, I am completely lost as to why you are using if statements in the first place. If this is a learning exercise, I would recommend using a switch statement such as this:
$Animal = "Zebra"
$Food = "Soup"
$output = ""
switch ($Animal){
"Chicken" { $output = "This $($Animal) eat $($Food)"; break}
"Cow" { $output = "This $($Animal) eat $($Food)"; break }
"Zebra" { $output = "This $($Animal) eat $($Food)"; break }
}
Write-Output $output
or just outputting the values without the unnecessary checking:
$Animal = "Zebra"
$Food = "Soup"
Write-Output "This $($Animal) eat $($Food)"
Upvotes: 3
Reputation: 11
Doug is correct, you missed some }
I have re-formatted it for you. I find this formatting helps to catch mistakes like this...
if ($Animal -eq "Chicken")
{
if ($Food -eq "Egg")
{
Write-Host "This chicken eats egg"
}
ElseIf ($Food -eq "Soup")
{
Write-Host "This chicken eats soup"
}
}
ElseIf ($Animal -eq "Cow")
{
if ($Food -eq "Egg")
{
Write-Host "This cow eats egg"
}
ElseIf ($Food -eq "Soup")
{
Write-Host "This cow eats soup"
}
}
ElseIf ($Animal -eq "Zebra")
{
if ($Food -eq "Egg")
{
Write-Host "This zebra eats egg"
}
ElseIf ($Food -eq "Soup")
{
Write-Host "This zebra eats soup"
}
}
Upvotes: 1