Powershell:记录我删除的文件

时间:2016-10-06 14:44:32

标签: powershell

PowerShell新手并需要一些帮助。我的脚本搜索TEST文件夹和子文件夹,然后删除超过21天的文件。我想将所有已删除的文件记录在日志文件中。

<table>
    <tr id="1">
       <td id="fav_ali" data-fav_ico="0"><img src="img/tmp.png" id="fav_off" class="img_btn" title="add to fav"/></td>
       <td id="des_ali" class="cg_ott">aaaa</td>
    </tr>
    <tr id="2"> 
       <td id="fav_ali" data-fav_ico="1"><img src="img/tmp.png" id="fav_on" class="img_btn" title="del from fav"/></td>
       <td id="des_ali" class="cg_na">aaaaa</td>
    </tr>    
</table>

2 个答案:

答案 0 :(得分:1)

Add-Content $filename $value会做到的!

cls 
$Now = Get-Date 
$Days = "21" 
$Targetfolder = "c:\TEST" 
$LogFile = "C:\DeletedFiles.txt"
#----- define LastWriteTime parameter based on $Days ---# 
$LastWrite = $Now.AddDays(-$Days) 
#----- get files based on lastwrite filter and specified folder ---# 
$Files = Get-Childitem $TargetFolder -Include $Extension -Exclude *.xml -Recurse | 
        where {$_.LastWriteTime -le "$LastWrite"} 
        foreach ($File in $Files) { 
            if ($File -ne $Null) { 
                Add-Content $LogFile $File.FullName
                write-host "Deleting File --> $File" -ForegroundColor "Green" Remove-Item $File.FullName | out-null 
            } 
        } 

如果您想使其更加健壮,可以在文件中添加时间戳,以便了解它何时被删除。

$myDate = get-date -format -g
$content = $myDate  + "   " + $File.FullName
Add-Content $LogFile $content

答案 1 :(得分:0)

将输出写入日志文件的最简单方法是使用 -Verbose,然后在命令后使用 Write-Verbose 或 4>

Remove-Item $File.FullName -Verbose 4> $log_file_path