首页 > 解决方案 > 在 PowerShell 的 ForEach 循环中实现 -verbose 输出?

问题描述

我正在编写一个脚本来将一些超过 6 个月的日志文件存档到一个 7zip 文件,然后删除原始文件。我想实现一个 -verbose 输出,以便创建一个日志文件,列出哪些文件已成功存档和删除。已删除文件的输出报告正确,但是我不知道在代码中的何处实现 -verbose 以确认存档到 7z 文件。

# start logging of archived files and specify log location for each day 
Start-transcript C:\Temp\LogArchiveTesting\Logs\Archived_Server_Logging_$(get-date -format ddMMMyyyy).log


# set folder path
$log_path = "C:\Temp\LogArchiveTesting\*.*"
$zip_path = "C:\Temp\LogArchiveTesting\Archive\*.7z"
$target_path = "C:\Temp\LogArchiveTesting\Archive\"

# set min age of files
$max_months = "-6"
$delete_max_days = "-365"

# get the current date
$curr_date = Get-Date

# determine how far back we go based on current date
$zip_date = $curr_date.AddMonths($max_months)
$delete_zip_date = $curr_date.AddDays($delete_max_days)

#$zip_date = (Get-Date).AddMonths(0).Month

# filter files
Get-ChildItem $log_path | Where-Object { ($_.LastWriteTime -lt $zip_date) -and ($_.psIsContainer -eq $false)}|

  ForEach {
    $Zip = $target_path + "{0:yyMM}_{0:MMM}Server Logging.7z" -f $_.LastWriteTime
    & "C:\Program Files\7-Zip\7z.exe" u -mx9 -t7z -m0=lzma2  $Zip $_.FullName |Out-Null
    If ($LastExitCode -eq 0) { Remove-Item $_.FullName }
  }

$deletefile = Get-ChildItem $zip_path | Where-Object { $_.LastWriteTime -lt $delete_zip_date } | Remove-Item -verbose

#Stops logging of archived files
stop-transcript

标签: powershell7zipverbose

解决方案


推荐阅读