Добавить метку времени в выходной файл журнала перед каждым объектом - PullRequest
0 голосов
/ 02 марта 2020

У меня есть скрипт 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 

Ответы [ 2 ]

0 голосов
/ 02 марта 2020

Вы можете сделать это в своем коде, добавив foreachl oop

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 
0 голосов
/ 02 марта 2020

Да, вы можете добавить текущую дату к каждой строке. Для лучшего понимания я бы назначил временную переменную. Вы можете сделать это с каждой строкой кода:

$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

...