2

I've been strugling on a little thing for few hours now, and I wanted to know if one of you have the solution (maybe i'm missing a little thing)

I got a switch for setting the condition in a IF but seems it doesn't interprete it as a if condiction

switch ( $CampaignStatus )
{
    "Complete"   { $CampainCondition = ($DateStr -eq (get-date  -Format "MM/dd/yyyy"))   }
    "Incomplete" { $CampainCondition =  ($DateStr -eq (get-date  -Format "MM/dd/yyyy"))   }
    "InProgress" { $CampainCondition =  ($DateStr -gt (get-date  -Format "MM/dd/yyyy"))   }
}
foreach($c in $CampaignList) {  
 $index = $index +1

    $DateStr = ConvertToFriendlyDate -Date $c.deadline
    if ($CampainCondition) { blablabla}

Any idea ?

I tried with quotes, without etc

3
  • 4
    $DateStr -gt (get-date -Format "MM/dd/yyyy") won't work correctly. For comparing dates in string format, the year must come first. Commented Nov 10, 2022 at 15:47
  • 2
    It's a bit odd that you're comparing two of the same conditions as well. Complete, and Incomplete will return the same value. So, you really only need one. Another odd thing is your switch statement seems to be before your assignment of $DateStr, yet you are using that result to compare inside your switch. Can you elaborate more on that? Commented Nov 10, 2022 at 15:49
  • 1
    @AbrahamZinala Yeah, but there is another switch which will pass in param another array, it's the same condition for different array and values Commented Nov 10, 2022 at 16:02

1 Answer 1

4

You're looking for Script Blocks to store those expressions and later evaluate them:

$CampainCondition = switch ( $CampaignStatus ) {
    "Complete"   { { $DateStr -eq (Get-Date -Format "MM/dd/yyyy") } }
    "Incomplete" { { $DateStr -eq (Get-Date -Format "MM/dd/yyyy") } }
    "InProgress" { { $DateStr -gt (Get-Date -Format "MM/dd/yyyy") } }
}

Then for evaluation, you can use the call operator &:

foreach($c in $CampaignList) {
    $index   = $index++
    $DateStr = ConvertToFriendlyDate -Date $c.deadline
    if(& $CampainCondition) {
        <# blablabla #>
    }
    <# blablabla #>
}

As for the conditions themselves, instead of converting the date into a specific format (Get-Date -Format "MM/dd/yyyy") and then comparing that string with $DateStr, it would a much better idea to parse $DateStr as a DateTime instance and compare that against today's date.

Sign up to request clarification or add additional context in comments.

2 Comments

-gt is not gonna work as expected on mixed-endian date formats
@MathiasR.Jessen well I agree, I added an update regarding that, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.