Ros*_*ons 1 powershell switch-statement
我正在创建一个脚本,该脚本将根据条件更新 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}
}
}
Run Code Online (Sandbox Code Playgroud)
一$endIRs开始保存了过去 12 小时内记录的一系列高优先级“事件”。如果没有,一切都将是默认设置的“绿色”。
我试图通过该语句实现的switch目标是if (($classification -eq 'Reports') -and ($priority -eq '1')) {'change the cell colour and text'}我可以自己完成,但我需要它来检查优先级是“1”还是“2”,并对电子表格中的“报告”分类单元格执行不同的操作。
可以在声明if中做一个声明吗switch,或者有更好的方法吗?
您可以使用$true作为switch条件并将检查作为脚本块值:
switch ($true) {
{($classification -eq 'Reports') -and ($priority -eq '1')} {
...
}
# ...
# more switch statements to go here
# ...
default {
...
}
}
Run Code Online (Sandbox Code Playgroud)
不过,我从来没有真正喜欢过这种方法。对我来说总是看起来像一个丑陋的黑客。我更喜欢一个if..elseif..else控制结构:
if ($classification -eq 'Reports' -and $priority -eq '1') {
...
} elseif (...) {
...
} elseif (...) {
...
} else {
...
}
Run Code Online (Sandbox Code Playgroud)
编辑:当然,您也可以使用“常规”switch语句并在操作脚本块中嵌套其他条件:
switch ($classification) {
'Reports' {
if ($priority -eq '1') {
...
} elseif ($priority -eq '2') {
...
}
}
# ...
# more switch statements to go here
# ...
default {
...
}
}
Run Code Online (Sandbox Code Playgroud)