首页 > 解决方案 > 用于系统日志管理的 Powershell 循环

问题描述

如果我运行下面的脚本,它将执行我需要的所有任务。我需要任务每 15 秒循环运行一次。当我添加任何类型的循环时,循环只会卡在脚本的一部分上,不再按预期运行。我希望从上到下循环整个脚本。当前脚本此时没有任何循环。任何帮助将不胜感激。

# Syslog Management. Automate has a max size of 977KB before it dumps everything into a file called Syslogold.txt
# If Syslogold.txt already exists it will be overwriten and logs will be gone.
# Script below will move syslogold.txt into syslog folder where it will be renamed to Syslog-(CurrentDate).TxT
# When ever a new Syslogold.txt is generated by Automate, this script will append the output to a daily file in a monthly folder.
# On the first day of every month, the previous month will be zipped and archived. 
#
$LastMonth = (Get-Date).AddMonths(-1).ToString('MMM-yyyy')
$CurrentSyslogFolder = "C:\Windows\LTsvc\Syslogs\Syslogs-$(Get-Date -Format "MMM-yyyy")"
$OldDirectory = "C:\Windows\LTsvc\Syslogs\Syslogs-$LastMonth"
$CurrentLog = "Syslog-$(Get-Date -Format "dd-MMM-yyyy").txt"
$OldLog = "C:\Windows\LTSvc\syslogold.txt"
$SyslogArchive = "C:\Windows\LTSvc\Syslogs\Archive\Syslog-$LastMonth.zip"

do{
$TestPath01 = Test-Path -Path $CurrentSyslogFolder
$TestPath02 = Test-Path -Path $CurrentSyslogFolder\$CurrentLog
$TestPath03 = Test-Path -Path $OldLog
$TestPath04 = Test-Path -Path $OldDirectory

if($TestPath01)
    {
    write-host "Syslog directory current."
    }
else
    {
    write-host "Current syslog directory is for last month. Creating new folder."
    New-Item -ItemType Directory -Force -Path $CurrentSyslogFolder
    }
if(($TestPath02) -and ($TestPath03))
    {
    write-host "Automate syslog archive found"
    write-host "Daily syslog Found."
    write-host "Appending Automate archive with daily syslog"
    Add-Content -Path $CurrentSyslogFolder\$CurrentLog -Value ""
    Get-Content -Path $OldLog | Add-Content -Path $CurrentSyslogFolder\$CurrentLog
    Remove-Item -Path $OldLog
    start-sleep -Seconds 15
    }
else
    {
    write-host "Automate syslogs active."
    write-host "Waiting for Automate to archive syslogs."
    if ($TestPath03)
    {
    Write-Host "Automate has completed archiving Syslogs." 
    Write-Host "Moving archive to daily syslog."
    Write-host "Daily syslog missing. Creating daily syslog now"
    Move-Item $OldLog -Destination $CurrentSyslogFolder\$CurrentLog
    }
    }
if($TestPath04)
    {
    write-host "Last months directory found."
    Write-Host "Compressing last months directory"
    Compress-Archive -Path "$OldDirectory" -DestinationPath "$SyslogArchive"
    Write-host "Moving compressed directory to archive"
    Write-host "Cleaning up files"
    Remove-Item -Path "$SyslogDirectory\Syslogs-$LastMonth" -Recurse
    Write-host "Cleanup completed"
    start-sleep -Seconds 15
    }
else
    {
    Write-host "Will try again in 15 seconds"
    start-sleep -Seconds 15
    }
}until($infinity)

标签: powershellarchivesyslog

解决方案


老实说,最好的方法是计划任务ScheduledTask 但您也可以使用 do 或while

do{ YOURSCRIPT start-sleep -Seconds 15 }until($infinity)


推荐阅读