1

I'm creating a script that will be updating an Excel spreadsheet depending on conditions.

This is what I currently have:

if ($endIRs -ne $null) {
$endIRs | ForEach-Object {
    try {
        $classification = $_.Classification
        $priority = $_.Priority
        $title = $_.Title 
        $id = $_.Id

        switch ($classification) {
            {($_ -eq 'Reports') -and ($priority -eq '1')} {
            $GeAppsReportSheet.Cells.Item(8,2).Interior.ColorIndex = 3
            $GeAppsReportSheet.Cells.Item(8,2) = 'RED'
            }
            #more switch statements to go here
        }
     catch {#catch tickets with $classification not listed}
    }
}

The $endIRs at the start holds a series of high priority 'incidents' that have been logged in the last 12 hours. If there is none, everything will be 'GREEN' which is set by default.

What I am trying to achieve with the switch statement is if (($classification -eq 'Reports') -and ($priority -eq '1')) {'change the cell colour and text'} which I can do on its own, but I need it to check if the priority is "1" or "2" and do something different against the "Reports" classification cell in the spreadsheet.

Can you do an if statement within the switch statement, or is there a better way to do it?

0

1 Answer 1

5

You can use $true as the switch condition and put the checks as scriptblock values:

switch ($true) {
    {($classification -eq 'Reports') -and ($priority -eq '1')} {
        ...
    }
    # ...
    # more switch statements to go here
    # ...
    default {
        ...
    }
}

I never really liked this approach, though. Always looked like an ugly hack to me. I'd prefer a if..elseif..else control structure:

if ($classification -eq 'Reports' -and $priority -eq '1') {
    ...
} elseif (...) {
    ...
} elseif (...) {
    ...
} else {
    ...
}

Edit: Of course you can also use a "regular" switch statement and nest other conditionals in the action scriptblocks:

switch ($classification) {
    'Reports' {
        if ($priority -eq '1') {
            ...
        } elseif ($priority -eq '2') {
            ...
        }
    }
    # ...
    # more switch statements to go here
    # ...
    default {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry for my poor explanation Matt. @Ansgar - my thoughts were something along the lines of: switch ($classification) { 'Reports' {if ($priority -eq '1') {colour cell RED} elseif ($priority -eq '2') {colour cell AMBER}} } - that sort of thing, if that makes sense?
@RossLyons That's certainly an option. See updated answer.

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.