2017-07-28 106 views
0

所有的工作必須記錄下來,我試圖列出文件夾的內容,刪除某些文件,在我的例子中有3個我想要刪除的文件夾內的文件。然後列出每個文件以查看該文件是否存在(未被刪除)或不存在(被刪除)。Powershell:獲取文件夾的內容,刪除特定文件,驗證文件是否被刪除/存在

這是我到目前爲止做:

$ErrorActionPreference = "SilentlyContinue"; 
    $mindump = gci c:\test1 -recurse -Include Minidump*.dmp 
    remove-item $mindump -force -whatif 

當我想驗證一個文件被刪除或不:

$mindump | % { $a =$_; test-path $_ | where {$_ -eq $True} | %{ write-host $a File still exists or a new file with the same name was created}} 

它適用於找出如果該文件仍然存在,但如果我嘗試類似:

$mindump | % { $a =$_; test-path $_ | where {$_ -eq $True} | %{ write-host $a File still exists or a new file with the same name was created} | % else { write-host $a File was deleted/does not exists} } 

它根本不起作用。我還能做其他什麼事情?

+0

你爲什麼要將'$ _'('$ PSItem')賦值給一個變量? – TheIncorrigible1

+0

@TheIncorrigible1你是對的,我忘了刪除它,我離開了$ a = $ _,因爲我正在做其他一些測試 – Eduardo

回答

2

您有一個簡單的語法錯誤。您不能使用else作爲對ForEach-Object循環的響應,您將需要使用If語句。

$mindump | % { 
    $a =$_ 
    If(test-path $_){ 
     write-host $a File still exists or a new file with the same name was created 
    } else { 
     write-host $a File was deleted/does not exists 
    } 
} 
+0

我在閱讀迴應之前幾秒鐘找到了完全相同的結論。謝謝! – Eduardo

相關問題