电源外壳开关 - 多个子句



我正在创建一个脚本,该脚本将根据条件更新Excel电子表格。

这是我目前拥有的:

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}
}
}

开头的$endIRs包含过去 12 小时内记录的一系列高优先级"事件"。如果没有,则所有内容都将是默认设置的"绿色"。

我试图通过switch语句实现的是我可以自己做的if (($classification -eq 'Reports') -and ($priority -eq '1')) {'change the cell colour and text'},但我需要它来检查优先级是"1"还是"2",并对电子表格中的"报告"分类单元格执行不同操作。

你能在switch语句中做一个if语句吗,或者有更好的方法来做吗?

您可以使用$true作为switch条件,并将检查作为脚本块值:

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

不过,我从来都不喜欢这种方法。对我来说总是像一个丑陋的黑客。我更喜欢if..elseif..else控制结构:

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

编辑:当然,您也可以使用"常规"switch语句并在操作脚本块中嵌套其他条件:

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

最新更新