PowerShell 删除文件(如果存在)

Tom*_*Tom 16 powershell

你能帮我写一个 powershell 脚本吗?我想检查是否存在多个文件,如果存在则删除文件。如果文件已被删除,则提供信息;如果文件不存在,则提供信息。

我找到了下面的脚本,它只适用于 1 个文件,如果文件不存在,它不会给出消息。你能帮我调整一下吗?我想删除文件 c:\temp\1.txt、c:\temp\2.txt、c:\temp\3.txt(如果存在)。如果这些不存在,则会显示一条消息,表明它们不存在。如果文件不存在,Powershell 不应引发错误或停止。

$FileName = "C:\Test\1.txt"
if (Test-Path $FileName) {
   Remove-Item $FileName -verbose
}
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!汤姆

Yve*_*ndo 15

您可以创建要删除的路径列表并像这样循环遍历该列表

$paths =  "c:\temp\1.txt", "c:\temp\2.txt", "c:\temp\3.txt"
foreach($filePath in $paths)
{
    if (Test-Path $filePath) {
        Remove-Item $filePath -verbose
    } else {
        Write-Host "Path doesn't exits"
    }
}
Run Code Online (Sandbox Code Playgroud)


Bow*_*ock 5

第 1 步:您需要多个文件。您可以通过两种方式做到这一点:

$files = "C:\file1.txt","C:\file2.txt","C:\file3.txt"
Run Code Online (Sandbox Code Playgroud)

这样就可以了,就是麻烦。更轻松?将所有文件放在一个 .csv 列表中,然后将其导入。请记住,第一行不会被读取,因为它考虑标题:

$files = Import-Csv "C:\yourcsv.csv"
Run Code Online (Sandbox Code Playgroud)

好的,第 2 步:现在您已获得文件,现在我们要循环它们:

Foreach ($file in $files) {
If (Test-Path $file) {
Remove-Item $file -verbose | Add-Content C:\mylog.txt }
else { Write-Host "$file not found" }}
Run Code Online (Sandbox Code Playgroud)

Foreach 循环将每个单独的“条目”放入一个变量中,并对它们执行您想要的任何操作。那应该做你想做的事。