【问题标题】:Add timestamp to output log file before each object在每个对象之前添加时间戳到输出日志文件
【发布时间】:2020-03-02 18:03:55
【问题描述】:

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

$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 

【问题讨论】:

  • 另外,将最后一行的(Get-Date).AddDays($limit) 更改为$limit,因为$limit 已经是要检查的日期。
  • 亲爱的西奥,感谢您的评论。我已按照您的指示更正了最后一行。

标签: powershell timestamp delete-file


【解决方案1】:

您可以通过添加 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 

【讨论】:

  • 亲爱的 Vad,感谢您的回答。这正是我想要的。
【解决方案2】:

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

$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

【讨论】:

  • 亲爱的 Nicicalu,感谢您的回复。这不是我想要的,但很高兴知道如何在 powershell 中使用函数。
  • 哦,好吧,在我阅读了其他答案后,我发现了您的目标。
猜你喜欢
  • 2012-12-24
  • 2021-07-08
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
相关资源
最近更新 更多