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

Nested IF ELSE condition and logic not working for some reason

为什么下面的 ELSE 不起作用?语法和流程似乎符合条件。我有兴趣了解为什么下面的逻辑不起作用。

当前输出
文件存在!*

预期输出:
文件存在!
这个条件也是成立的。但被脚本忽略了!


出于某种原因,“ELSE”行未在下面执行...即使我已经确认 $File 存在并且 $FileLeaseGood = $null

按照我阅读脚本的方式,“ELSE”特定于 $FileLeaseGood IF 语句,而不是 $File exists 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!"
    }

您的意思是要发生这种情况吗?如果您的 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 不存在,您在此处设置的 else 条件将会触发。这应该足以说明发生了什么以及您需要做些什么来解决它。

马特最后的解释让我知道我做错了什么;现在,它完全有道理。我只是把 ELSE 放在了错误的地方。下面是我 "EXPECTED" 最初的工作方式。

$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!"
}
}