Stanko Maksimovic
Stanko Maksimovic

Reputation: 17

How to get powershell log

I have a PowerShell function that will delete folders that haven't been modified for a certain period.

I would like to know how to get output/logs to .txt or .csv file that will show me what folders were deleted and at what time. I have tried Start-Transcript but it will only show errors not success.

$daysToKeep = -15
$foldersToKeep = 3
$Location = "C:\Users\Administrator\Desktop\Batch"
$folderList = Get-ChildItem -Path $Location -Recurse -Directory
                                                      
$folderList | Sort-Object CreationTime -Descending | 
Select-Object -Skip $foldersToKeep |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays($DaysToKeep) } | 
Remove-Item -Recurse 

Upvotes: 0

Views: 149

Answers (1)

Steven
Steven

Reputation: 7057

If you put the files into a loop you can create a custom object with a DeleteTime property:

$LogFile = 'C:\temp\FileDeleteLog.csv'
$daysToKeep = -15
$DateBound = (Get-Date).AddDays($daysToKeep)
$foldersToKeep = 3
$Location = "C:\Users\Administrator\Desktop\Batch"

Get-ChildItem -Path $Location -Recurse -Directory |
Sort-Object CreationTime -Descending |
Select-Object -Skip $foldersToKeep |
Where-Object { $_.LastWriteTime -lt $DateBound } | 
ForEach-Object{
    [PSCustomObject]@{
        FolderPath = $_.FullName
        LastWriteTime = $_.LastWriteTime
        DeleteTime = (Get-Date)
    }

    Remove-Item $_.FullName -Recurse
} |
Export-Csv -Path $LogFile -NoTypeInformation

I can imagine there are quite a few ways to do this, this is just one. We could have used Select-Object to add the time stamp within the existing pipeline. However, if the process takes a long time you may develop unacceptable gaps between those timestamps and when the folder was actually deleted. For now, I think above will be more accurate.

Upvotes: 1

Related Questions