Powershell:获取文件夹的内容,删除特定文件,验证文件是否被删除/存在
问题描述:
所有的工作必须记录下来,我试图列出文件夹的内容,删除某些文件,在我的例子中有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} }
它根本不起作用。我还能做其他什么事情?
答
您有一个简单的语法错误。您不能使用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
你为什么要将'$ _'('$ PSItem')赋值给一个变量? – TheIncorrigible1
@TheIncorrigible1你是对的,我忘了删除它,我离开了$ a = $ _,因为我正在做其他一些测试 – Eduardo