在每个对象之前将时间戳添加到输出日志文件

Add timestamp to output log file before each object

我有一个 powershell 脚本可以删除超过 180 天的文件和文件夹,我想在日志文件中的每个对象之前添加删除日期和时间。这可能吗?

$limit = (Get-Date).AddDays(-180)
$path = "D:\RAZMJENA DOKUMENATA"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Verbose 4>&1 | out-file d:\Delete_script\deleted_files_log.txt -append 

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse -Verbose 4>&1 | out-file d:\Delete_script\deleted_files_log.txt -append 

#Delete remaining empty folders older than 180 days.
Get-ChildItem -Path $path -Directory -Recurse | Where {$_.lastwritetime -lt (Get-Date).AddDays($limit) -and (gci $_.fullName).count -eq 0} | Remove-Item -Force -Verbose 4>&1 | out-file d:\Delete_script\deleted_files_log.txt -append 

是的,您可以将当前日期添加到每一行。为了更好地理解,我会分配一个临时变量。您可以对每一行代码执行此操作:

$tmp = Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Verbose 4>&1 
$date = Get-Date -Format "MM/dd/yyyy HH:mm" #Format the Date
"$date --> $tmp" | out-file d:\Delete_script\deleted_files_log.txt -append #Append to logfile

或者更好的是,创建一个您可以在每次要记录时调用的函数:

function logToFile($tmp){
      $date = Get-Date -Format "MM/dd/yyyy HH:mm" #Format the Date
      "$date --> $tmp" | out-file d:\Delete_script\deleted_files_log.txt -append 
}

然后你可以随时调用它:

$tmp = Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Verbose 4>&1 
logToFile $tmp

如果您想要其他格式的日期,您可以在此页面上获得更多信息: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-date?view=powershell-7

您可以在代码中添加 foreachloop

Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Verbose 4>&1|foreach{($_.Message).Tostring()+" "+((Get-Date).DateTime).ToString()} | out-file d:\Delete_script\deleted_files_log.txt -append