2015-06-26 33 views
0

爲什麼ELSE在以下工作?語法和流程似乎對條件是正確的。請不要發佈備用解決方案,而不必解釋下面的邏輯不起作用的原因。理想情況下,最不復雜的例子(這是人類可讀的)將非常感激。嵌套的IF ELSE條件和邏輯因某種原因不起作用

電流輸出
文件存在*

預期輸出:
文件存在!
這種情況也是如此。但被腳本忽略!


無論出於何種原因,「ELSE」行不執行下面...... 雖然香港專業教育學院已經證實,$文件存在,$ FileLeaseGood = $空

的我的方式閱讀我的腳本,「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!" 
    } 
+0

運行此操作後,您的輸出是什麼?哪個寫主機會執行? – rageit

+0

'write-host'!='寫主機'? –

+0

他們的方式這是編碼,如果該文件不存在「的條件是真的」。這只是支架放置問題。 – Matt

回答

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不存在,您在這裏的其他條件將會觸發。這應該是一個足夠的解釋,以涵蓋正在發生的事情以及您需要做什麼來解決問題。

+0

哎呀...我只是仔細閱讀你所說的話。如果$ FileLeaseGood不存在,我期待ELSE具體。不,如果$文件不存在。我究竟做錯了什麼? – MKANET

+0

@MKANET你把一個括號放在錯誤的地方,所以else子句被應用到'if(Test-Path $ File)'而不是內部,如果你喜歡它。使用我的_first_代碼片段,它應該按照您的意圖工作 – Matt

-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!" 
} 
} 
+0

而不是重新張貼別人的解決方案,請[接受他們的答案](http://meta.stackoverflow.com/a/5235)。 –