Powershell 将elseif更改为else语句

Powershell 将elseif更改为else语句,powershell,Powershell,我是PowerShell的新手,从学校的一位讲师那里得到了一些反馈 考虑以下简单代码: if (!(Test-Path -Path $installDirectory)) { Write-Output "Creating directory $installDirectory" New-Item -Path $installDirectory -ItemType Directory } elseif (Test-Path -Path $installDirectory) {

我是PowerShell的新手,从学校的一位讲师那里得到了一些反馈

考虑以下简单代码:

if (!(Test-Path -Path $installDirectory)) {
    Write-Output "Creating directory $installDirectory"
    New-Item -Path $installDirectory -ItemType Directory
}

elseif (Test-Path -Path $installDirectory) {
     Write-Output "Directory $installDirectory already exists."
}
讲师说应将
elseif
更改为
else
,以改进我的代码

这是正确的吗

else { 
    Write-Output "Directory $installDirectory already exists."
}

谢谢

如果和
elseif
条件相互排斥,则您的
检查的状态是相互排斥的。目录
$installDirectory
存在或不存在。因此,无需检查两次。如果条件
测试路径-Path$installDirectory
为true,则否定条件将自动为false

为清楚起见,我还将切换您的条件,以避免在
if
条件中出现否定

if (Test-Path -Path $installDirectory) {
    Write-Output "Directory $installDirectory already exists."
} else {
    Write-Output "Creating directory $installDirectory"
    New-Item -Path $installDirectory -ItemType Directory
}

为什么不试着运行它呢?如果您有两个以上的条件要测试,您将需要
elseif
。对于
测试路径
,您只有两个结果,路径存在或不存在
Else
在这里应该可以。如果您的模式是
If(a){…}elseif(!a){…}
那么是的,您的代码可以通过删除第二个If来改进。如果表达式有可能在两个值之间神奇地翻转状态(即,您正在检查两个随机值),则不会,它不会得到改进,但在本例中会得到改进。你的讲师是对的,尽管他可能应该告诉你原因,而不仅仅是“去做”。养成质疑建议的习惯,而不是“我不确定这是否正确”,而是问“为什么正确?”在这种情况下,你应该问你的讲师。