嵌套的IF ELSE条件和逻辑由于某种原因不起作用

时间:2015-06-26 17:41:20

标签: powershell if-statement syntax conditional-statements

为什么ELSE不在下面工作?语法和流程似乎对条件正确。请不要发布替代解决方案,而不解释为什么下面的逻辑不起作用。理想情况下,最不复杂的例子(人类可读)将非常受欢迎。

当前输出
文件存在!*

预期输出:
文件存在!
这种情况也是如此。但被脚本忽略了!

无论出于何种原因," ELSE"即使已经确认$ File存在且$ FileLeaseGood = $ null

,也不会在... 下执行

我正在阅读我的剧本的方式," ELSE"特定于$ FileLeaseGood IF语句,而不是$ File存在的IF语句。

$File = gi "P:\tmp\MKA.theme"
$lastWrite = (get-item $File).LastWriteTime
$timespan = new-timespan -hours 8
$FileLeaseGood = $NULL
if (((get-date) - $lastWrite) -le $timespan) {$FileLeaseGood = $True}

if (Test-Path $File) {
    write-host "File exists!"
    if ($FileLeaseGood) {

        write-host "File exists! and File Lease still good"

    }} else {

        #Why doesn't this else condition work???
        Write-host "This condition is also true. But ignored by script!"
    }

2 个答案:

答案 0 :(得分:2)

你的意思是发生这种情况吗?如果你的if / else要完全嵌套,你的一个结束括号不在正确的位置。代码按照设计执行。听起来像你意味着发生的事情是这样的。

if (Test-Path $File) {
    write-host "File exists!"
    if ($FileLeaseGood) {
        write-host "File exists! and File Lease still good"        
    } else {
        Write-host "This condition is true."
    }
}

稍微改变间距和压痕,证明一点,这就是你之前的比较。

if (Test-Path $File) {
    write-host "File exists!"
    if ($FileLeaseGood) {
        write-host "File exists! and File Lease still good"
    } # <--- New Line place here is the visual change you should notice.
} else {
    #Why doesn't this else condition work???
    Write-host "This condition is true. But ignored!"
}

如果$file不存在,那么此处的其他条件将会触发。这应该是一个充分的解释,以涵盖正在发生的事情和你需要做些什么来解决它。

答案 1 :(得分:-1)

马特的最后一个解释让我知道我做错了什么;现在,它非常有意义。我只是把ELSE放在了错误的地方。以下是我“期望”它最初工作的方式。

$File = gi "P:\tmp\MKA.theme"
$lastWrite = (get-item $File).LastWriteTime
$timespan = new-timespan -hours 8
$FileLeaseGood = $NULL
if (((get-date) - $lastWrite) -le $timespan) {$FileLeaseGood = $True}

if (Test-Path $File) {
    write-host "File exists!"
    if ($FileLeaseGood) {
        write-host "File exists! and File Lease still good"
    } else {Write-host "This condition is true. But not ignored anymore!"
}
}