将elseif更改为else语句

时间:2017-11-09 12:29:19

标签: powershell

我是PowerShell的新手,并得到了学校讲师的一些反馈。

考虑这个简单的代码:

http

讲师说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

由于

1 个答案:

答案 0 :(得分:4)

ifelseif条件检查的状态是互斥的。目录$installDirectory存在,或者它不存在。因此,无需检查两次。如果条件Test-Path -Path $installDirectory为真,则否定条件自动为假。

为了清楚起见,我还要切换您的条件,以避免if条件中的否定。

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