Noveris.SvcProc.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
<# #> #Requires -Modules @{"ModuleName"="Noveris.Logger";"RequiredVersion"="0.6.1"} ######## # Global settings $ErrorActionPreference = "Stop" $InformationPreference = "Continue" Set-StrictMode -Version 2 <# #> Function Invoke-ServiceRun { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateNotNull()] [ScriptBlock]$ScriptBlock, [Parameter(Mandatory=$false)] [ValidateNotNull()] [int]$Iterations = -1, [Parameter(Mandatory=$false)] [ValidateSet("Start", "Finish")] [string]$WaitFrom = "Start", [Parameter(Mandatory=$false)] [ValidateNotNull()] [int]$WaitSeconds = 0, [Parameter(Mandatory=$false)] [ValidateNotNull()] [string]$LogPath = "", [Parameter(Mandatory=$false)] [int]$RotateSizeKB = 0, [Parameter(Mandatory=$false)] [int]$PreserveCount = 5 ) process { # Are we running indefinitely? [int]$count = $Iterations $infinite = $false if ($count -lt 0) { $infinite = $true } # Set up log rotation arguments $rotateArgs = $null if (![string]::IsNullOrEmpty($LogPath)) { $rotateArgs = @{ LogPath = $LogPath PreserveCount = $PreserveCount RotateSizeKB = $RotateSizeKB } } while ($infinite -or $count -gt 0) { # Capture start of script run $start = [DateTime]::Now Write-Verbose ("Start Time: " + $start.ToString("yyyyMMdd HH:mm:ss")) # Rotate log if ($null -ne $rotateArgs) { Reset-LogFileState @rotateArgs } # Run script block and redirect output as string try { Write-Verbose "Running script block" if ([string]::IsNullOrEmpty($LogPath)) { & $ScriptBlock *>&1 | Format-RecordAsString -DisplaySummary | Out-String -Stream if (!$?) { Write-Information "Script returned error" } } else { & $ScriptBlock *>&1 | Format-RecordAsString -DisplaySummary | Out-String -Stream | Tee-Object -Append -FilePath $LogPath if (!$?) { Write-Information "Script returned error" } } } catch { Write-Information "Script threw error: $_" } # Capture finish of script run $finish = [DateTime]::Now Write-Verbose ("Finish Time: " + $finish.ToString("yyyyMMdd HH:mm:ss")) if ($count -gt 0) { $count-- } # Sleep for next iteration if we have iterations remaining # or are infinite (-1). if ($infinite -or $count -gt 0) { # Calculate the wait time $relative = $finish if ($WaitFrom -eq "Start") { $relative = $start } # Determine the wait time in seconds $wait = ($relative.AddSeconds($WaitSeconds) - [DateTime]::Now).TotalSeconds Write-Verbose "Next iteration in $wait seconds" if ($wait -gt 0) { # Wait until we should run again Write-Verbose "Starting sleep" Start-Sleep -Seconds $wait } } } } } |