Powershell log deleted files Powershell log deleted files powershell powershell

Powershell log deleted files


First you will need a log-message type function in your script that will log the message to a .log file. Then chekc if the file exists and if not then create a file.

Then just before you delete your file with Remove-Item command you can use Log-Message function to log message to the log file.

% { (Log-Message "Deleting File $_"); $_ }

Complete script

$path = "C:\test\1"$keep = 3$strLogFileName   = "c:\test\yourlogfile.log";function Log-Message{   Param ([string]$logtext)   Add-content $strLogFileName -value $logtext}$dirs = Get-ChildItem -Path $path -Recurse | Where-Object {$_.PsIsContainer}foreach ($dir in $dirs) {    $files = Get-ChildItem -Path $dir.FullName | Where-Object {-not $_.PsIsContainer -and $_.name -like "*.zip"}    if ($files.Count -gt $keep) {        $files | Sort-Object CreationTime -desc| Select-Object -First ($files.Count - $keep) |         % { $dt=get-date;(Log-Message "Deleting File $_  on  $dt");$_ }| Remove-Item -Force     }}


You've got a good start here:

write-host “Deleting File $File” -foregroundcolor “Red”

Unfortunately Remove-Item doesn't have any output that you can mooch from, but you've already made your own output message so we can just build from that. You can pipe any output to a file by using Out-File. The append flag will attach the new content to the end of the file, and you do not have to check if the file exists.

Write-Output “Deleting File $File” | Out-File -Append logfile.txt

You don't even have to include Write-Output, if you want a shorter line.

Here is an example that shows where you need to add code. I've marked existing code with "...", and I've moved the deletion message into a variable so that you can reuse it at another location. This assumes that you've stored the selected filename in a variable.

...if ($files.Count -gt $keep) {    ...    $message = "Deleting File $File at "+(Get-Date)    $message | Out-File -Append logfile.txt }...