# # executeInterval.ps1 # # Start a program every couple of days. # Reads program name and interval from configuration file # # History: # ?.? Initial version without version number # 0.2 Added removal of backup of log-file before renaming log-file # 0.3 ... and now the removal of backup of log-file even works! # # Some constants $logFile="executeInterval.log" $cfgFile="executeInterval.cfg" $runFile="executeInterval.run" $interval=1 $programToExecute="echo `"NOTHING TO DO`"" $lastRun=$(Get-Date –month 1 -day 1 -year 1900) # Log file writer function writeToLog { "$(Get-Date -uformat `"%Y-%m-%d %T`"): $args" | Out-File -filePath $logFile -append } # check for existance and size of log file if ((Test-Path $logFile) -eq $false) { #create log file new-item -path . -name $logfile -type "file" > $null #write to log file writeToLog("-- New log file created") } elseif ( $(Get-Item $logFile).Length -gt 100000 ) { # remove backup file if necessary if ((Test-Path "$logFile.bak") -eq $true) { remove-item "$logFile.bak" } # move file to backup Rename-Item $logFile -newName "$logFile.bak" # create log file new-item -path . -name $logFile -type "file" > $null # write to log file writeToLog("-- Created Backup of log file and new log file") } # Log start time writeToLog("-- Script executeInterval started") writeToLog("Working in: $(Get-Location)") # Read configuration file; use defaults if nothing available if ((Test-Path $cfgFile) -eq $true) { # read file $lines = Get-Content $cfgFile $programToExecute = $lines[0] $interval = $lines[1] } else { writeToLog("No cfg file found - using defaults") } writeToLog("Using interval=$interval and programToExecute=$programToExecute") # Read run file; use defaults if nothing available if ((Test-Path $runFile) -eq $true) { # read file $lines = Get-Content $runFile $lastRun = [System.DateTime] $lines } else { writeToLog("No run file found - using defaults") } writeToLog("Using lastRun=$lastRun") # Check whether it is time to run the program if (($(Get-Date)-$lastRun).Days -ge $interval ) { &"$programToExecute" $lastRun=$(Get-Date) new-item -path . -name $runFile -type "file" -value "$lastRun" -force > $null writeToLog("External program executed with exit code $lastexitcode") } else { writeToLog("External program NOT executed") } # Log end time writeToLog ("-- Script executeInterval finished")