Reputation: 1298
Hi I have the below code and wanted to know the best way to replace it using a switch statement.This example I have 4 possible outcomes but I might end up with over 20 and if statements would get to cluttered .
$Des = "C:\tools\"
$DListFiles = Get-ChildItem $Des -EA 0
IF((Test-Path $Des)-ne $false -and $DListFiles -eq $null){$DDE = 1}
ElseIF((Test-Path $Des)-ne $false -and $DListFiles -ne $null){$DDE = 2}
ElseIF((Test-Path $Des)-eq $false){$DDE = 3}
Else{$DDE = 4}
write-host "$DDE"
Upvotes: 1
Views: 8504
Reputation: 1298
I ended up figuring some thing out that would work let me know what you all think.
$Des = "c:\test\"
$DListFiles = Get-ChildItem $Des -EA 0
Switch($Des)
{ {!$Des} {$DDE = 4; break}
{((Test-Path $Des)-ne $false -and $DListFiles -eq $null)} {$DDE = 1; break}
{((Test-Path $Des)-ne $false -and $DListFiles -ne $null)} {$DDE = 2; break}
{((Test-Path $Des)-eq $false)} {$DDE = 3; break}
}
$DDE
Upvotes: 1
Reputation: 37790
For the example that you posted, personally I would use a nested if to make the logic clearer:
If(Test-Path $Des){
If($DListFiles -eq $null){
$DDE = 1
}Else{
$DDE = 2
}
}Else{
If($DListFiles -eq $null){
$DDE = 3
}else{
$DDE = 4
}
}
By the way, the way that you have it written does not give the logic that I think that you want. I don't believe you would ever get $DDE = 2. If I'm reading what you posted correctly, the logic table is posted below. Again, a Nested If would help sort it out.
Test-Path $Dlist is Null $DDE
TRUE TRUE 1
FALSE FALSE 3
TRUE TRUE 4
FALSE FALSE 3
Upvotes: 4