Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 替换多个if语句_Powershell_Powershell 4.0_Powershell Remoting_Cmdlet - Fatal编程技术网

Powershell 替换多个if语句

Powershell 替换多个if语句,powershell,powershell-4.0,powershell-remoting,cmdlet,Powershell,Powershell 4.0,Powershell Remoting,Cmdlet,我使用的是PS版本5.0,我有很多if语句,它们可能会随着时间的推移而增长 if ($hostname -like "**12*") { Write-Output "DC1" } elseif ($Hostname -like "**23*") { Write-Output "DC2" } elseif ($Hostname -like "**34*") { Write-Output "DC3" } elseif ($Hostname -like "**45*") {

我使用的是PS版本5.0,我有很多
if
语句,它们可能会随着时间的推移而增长

if ($hostname -like "**12*") {
    Write-Output "DC1"
} elseif ($Hostname -like "**23*") {
    Write-Output "DC2"
} elseif ($Hostname -like "**34*") {
    Write-Output "DC3"
} elseif ($Hostname -like "**45*") {
    Write-Output "DC4"
}
你能推荐一些更好的方法来编写相同的代码吗?

你可以使用语句。下面是一个使用
-Regex
标志的示例,因为看起来您只是在进行简单的匹配,然后可以删除
*
通配符

$hostname = 'asdf12asdf'
switch -Regex ($hostname) {
    "12" {Write-Output "DC1"}
    "23" {Write-Output "DC2"}
    "34" {Write-Output "DC3"}
    "45" {Write-Output "DC4"}
    Default {Write-Error "No Match Found"}
}
如果不需要多个匹配项,请添加一个
;在每个案例后中断
。例如,如果您有一个主机名,如
asdf12asdf34
语句
“12”{Write Output“DC1”;Break}
将阻止
12
34
的输出,则可以使用语句。下面是一个使用
-Regex
标志的示例,因为看起来您只是在进行简单的匹配,然后可以删除
*
通配符

$hostname = 'asdf12asdf'
switch -Regex ($hostname) {
    "12" {Write-Output "DC1"}
    "23" {Write-Output "DC2"}
    "34" {Write-Output "DC3"}
    "45" {Write-Output "DC4"}
    Default {Write-Error "No Match Found"}
}

如果不需要多个匹配项,请添加一个
;在每个案例后中断
。例如,如果您有一个主机名,例如
asdf12asdf34
语句
“12”{Write Output“DC1”;Break}
将阻止
12
34

的输出,您能建议switch语句在这里的样子吗?您能建议switch语句在这里的样子吗?