-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgimble_scriptlogger.ps1
More file actions
295 lines (267 loc) · 11.6 KB
/
gimble_scriptlogger.ps1
File metadata and controls
295 lines (267 loc) · 11.6 KB
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
<#
gimble - "To make holes as does a gimlet." - Lewis Carrol
A micro logging utility for Windows PowerShell with
unique logfile names and auto-purge by date and/or file-count.
https://github.com/valleyspirit/gimble
Version : v.0.1.0
Keith Mitchell valleyspirit@gmail.com; https://github.com/valleyspirit
This work is licensed under the Apache 2.0 License. You can copy and/or fork and/or
modify and/or use this code for anything, entirely at your own risk ONLY,
but a one-line attribute is requested in all relevant files:
[Sourced from|Inspired by|Modified from]: gimble https://github.com/valleyspirit/gimble by Keith Mitchell
Quick-Start Guide: Run gimble_scriptlogger.ps1 -usage
Documentation: See the gimble_README.km file in this directory.
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
Gimble: "To make holes as does a gimlet."
- Lewis Carrol
#>
param
(
[parameter(Mandatory=$false, ValueFromPipeline=$true)]
[alias("path")]
[String] $ps_gimble_logFilePath,
[parameter(Mandatory=$false, ValueFromPipeline=$true)]
[alias("ident")]
[String] $ps_gimble_identifierString = '',
[parameter(Mandatory=$false, ValueFromPipeline=$true)]
[alias("maxdays")]
[int] $ps_gimble_purgeDays = 0,
[parameter(Mandatory=$false, ValueFromPipeline=$true)]
[alias("maxfiles")]
[int] $ps_gimble_purgeFiles = 0,
[alias("purgeglobal")]
[Switch] $ps_gimble_purgeGlobal,
[alias("usage")]
[alias("get-help")]
[alias("help")]
[Switch] $ps_gimble_usage
)
function Show-Usage() {
$help_output = "
gimble - `"To make holes as does a gimlet.`" - Lewis Carrol
A micro logging utility for Windows PowerShell with
unique logfile names and auto-purge by date and/or file-count.
https://github.com/valleyspirit/gimble
Version: v.0.1.0
Keith Mitchell keith@undyne.com; https://github.com/valleyspirit
Usage:
When included in another powershell script,
gimble provides two simple functions:
LogAndOutput ($textBlock)
LogOnly ($textBlock)
Each script execution will create a log file in a directory
which you specify, with a filename like this:
MyScriptIdentifier_MyMachineName_2012-09-10_0145-48pm.txt
(if you've specified a script identifier)
or
MyMachineName_2012-09-10_0145-48pm.txt
(if you have not specified a script identifier)
Logfile filename Examples:
==========================
magus_2012-09-10_0145-48pm.txt (no identifier)
portquery_NDPRRBACKUP_2012-09-10_0200-41pm.txt (identifier, 'portquery')
The active gimble logfile is accessible in parent (calling) scripts
by name and by fully qualified path and name, as:
`$ps_gimble_Logfile
`$ps_gimble_QualifiedLogfile
I tried to make these variable names reasonably unique.
Any single-line or multi-line text that you pass to
LogAndOutput() will be written to that log, realtime,
as the script executes, and will also be written to
the console or standard out.
Any single-line or multi-line text that you pass to
LogOnly() will be written to that log, realtime,
as the script executes, but will not be written to
the console or standard out.
This script must be included (dot-sourced, etc) in your script
in which you'd like to use the two logging functions.
When your script runs, gimble will automatically create a new
logfile specific to that execution, and dynamically log
whatever your script tells it to.
Include Examples
================
. `$ps_CurrentPath\powershell_functions\gimble_scriptlogger.ps1 $ps_LogPath
. \util\gimble_scriptlogger.ps1 -path `'C:\Some Path\ToMy\LogFiles`'
. gimble_scriptlogger.ps1 `'C:\Some Path\ToMy\LogFiles`'
HELP PARAMETERS
===============
gimble_scriptlogger.ps1 -U[u]sage | -G[g]et-H[h]elp | -H[h]elp | U[u]usage | G[g]et-H[h]elp | H[h]elp
REQUIRED PARAMETER
==================
There is one required parameter: The path where you want your log files placed.
-path Fully qualified path/directory for Logfile output.
ALL PARAMETERS
==============
-path [String] Fully qualified path/directory for Logfile output.
-ident [String] Identifier, Log file prefix:
Identifier_MachineName_YYYY-MM-DD_HHMM-SSpm.txt
Used to identify a log-file as generated by a particular script
if you implement a shared logging directory.
-maxdays [Integer] logfile purge value, can be used along with -maxfiles.
Used to prevent your log file directory from filling up.
Maximum age of logfiles to keep in log directory, which have
the active Identifier in their name.
The -purgeglobal flag will change this behavior, to be
maximum age of any logfiles to keep in log directory.
[no value] = Do not perform any file purges by logfile count
0 = Do not perform any file purges by logfile count
-maxfiles [Integer] logfile purge value, can be used along with -maxdays.
Used to prevent your log file directory from filling up.
Maximum files to keep in log directory, which have
the active Identifier in their name.
The -purgeglobal flag will change this behavior, to be
maximum files to keep in log directory, with any filename.
[no value] = Do not perform any file purges by logfile count
0 = Do not perform any file purges by logfile count
More Include Examples (Quick Examples of Purge Settings)
========================================================
. gimble_scriptlogger.ps1 -path $ps_LogPath -ident 'bootstrapbldr' -maxdays 1 -purgeglobal
= Keep only today's script logs in the log folder (and, these logfiles have prefix 'bootstrapbldr').
. gimble_scriptlogger.ps1 $ps_LogPath 'bootstrapbldr' 1 0 -purgeglobal
= Same as above.
. gimble_scriptlogger.ps1 $ps_LogPath -maxfiles 50
= Keep a maximum of 50 text files in the log folder (and log files have no prefixes).
. gimble_scriptlogger.ps1 $ps_LogPath 'site-pings' -maxdays 30
= Keep text files with the filename prefix 'site-pings' in the log folder for 30 days.
. gimble_scriptlogger.ps1 $ps_LogPath 'site-pings' -maxfiles 10
= Keep a maximum of 10 text files with prefix 'site-pings' in the log folder.
. $ps_CurrentPath\powershell_functions\gimble_scriptlogger.ps1 $ps_LogPath 'wabe' -maxfiles 10 -purgeglobal
= Keep a maximum of 10 text files in the log folder (and, new logfiles have prefix 'wabe').
USAGE EXAMPLE
=============
LogAndOutput 'Copying files to development deploy...'
try {
foreach (`$filename in `$files) {
LogAndOutput (' --> Copying ' + `$filename)
Copy-Item `$repo\currentpath\img\`$filename `$deploypath\img -force | Out-Null
}
LogAndOutput 'Copied files to development deploy.'
}
catch {
LogAndOutput 'Error: Can not copy files to deploy location.'
LogOnly (`$error[0].Exception.Message)
LogAndOutput ('See the logfile at ' + `$ps_QualifiedLogfile + ' for more information.')
LogAndOutput 'Execution halting.'
Exit
}
"
$help_output
}
if (($ps_gimble_usage) -or ($ps_gimble_logFilePath.Trim() -eq '') -or ($ps_gimble_logFilePath -eq '?') -or ($ps_gimble_logFilePath.ToLower() -eq 'usage') -or ($ps_gimble_logFilePath.ToLower() -eq 'get-help') -or ($ps_gimble_logFilePath.ToLower() -eq 'help')) {
Show-Usage
exit
}
<#
Set stop on errors, for this script only.
#>
$local:ErrorActionPreference = "stop"
<#
Set local variables: Log file
#>
$ps_gimble_MachineName = gc env:computername
$ps_gimble_DateStamp = get-date -format yyyy-MM-dd_hhmm-sstt
$ps_gimble_Logfile = $ps_gimble_MachineName.ToLower() + '_' + $ps_gimble_DateStamp.ToString().ToLower() + '.txt'
if ($ps_gimble_identifierString.Trim() -ne '') {
$ps_gimble_Logfile = $ps_gimble_identifierString.ToLower() + '_' + $ps_gimble_Logfile
}
$ps_gimble_QualifiedLogfile = $ps_gimble_logFilePath + '\' + $ps_gimble_Logfile
<#
Create logging directory if it doesn't exist
Create logging file
#>
if (!(Test-Path -path $ps_gimble_logFilePath)) {
try {
New-Item $ps_gimble_logFilePath -type directory -force | Out-Null
}
catch {
Write-Host $error
}
}
try {
New-Item $ps_gimble_QualifiedLogfile -type file -force | Out-Null
}
catch {
Write-Host $error
}
<#
Files are purged each time this script is included.
i.e., each time your calling script runs.
#>
if (($ps_gimble_purgeFiles -gt 0) -or ($ps_gimble_purgeDays -gt 0)) {
# initially include all files for purging
$include = '*.txt'
# filter files for purging to just identifier-leading files, if -purgeglobal is not flagged
if (($ps_gimble_identifierString.ToLower().Trim() -ne '') -and (!($ps_gimble_purgeGlobal))) {
$include = $ps_gimble_identifierString.ToLower() + '_*.txt'
}
# begin purging
# purge by file count, if indicated
if ($ps_gimble_purgeFiles -gt 0) {
$allFiles = Get-Childitem ($ps_gimble_logFilePath + '\*') -include $include
$preserveCount = 1
foreach ($file in ($allFiles | Sort-Object LastWriteTime -descending)) {
if ($preserveCount -gt $ps_gimble_purgeFiles) {
try {
if (($file.Name) -and ($file.Name -ne '') -and ($file.Name -ne '\')) {
Remove-Item ($ps_gimble_logFilePath + '\' + $file.Name) -force -recurse | Out-Null
}
}
catch {
Write-Host $error
}
}
$preserveCount += 1
}
}
# purge by age (days-to-keep), if indicated
if ($ps_gimble_purgeDays -gt 0) {
$ps_gimble_purgeDate = (Get-date).AddDays(-($ps_gimble_purgeDays))
$filesToDelete = Get-Childitem ($ps_gimble_logFilePath + '\*') -include $include | Where {$_.LastWriteTime -le $ps_gimble_purgeDate}
foreach ($file in $filesToDelete) {
try {
if (($file.Name) -and ($file.Name -ne '') -and ($file.Name -ne '\')) {
Remove-Item ($ps_gimble_logFilePath + '\' + $file.Name) -force -recurse | Out-Null
}
}
catch {
Write-Host $error
}
}
}
}
<#
.SYNOPSIS
Logs a text block (including any line breaks)
To the end of an internally-determined log file.
(Realtime, reads and re-writes the file.)
#>
function LogOnly ($textBlock) {
$ps_gimble_LogFile_WriteLineCache = @()
$ps_gimble_LogFile_WriteLineCache += $textBlock
try {
Add-Content $ps_gimble_QualifiedLogfile $ps_gimble_LogFile_WriteLineCache
}
catch {
Write-Host $error
}
}
<#
.SYNOPSIS
Logs a text block (including any line breaks)
To the end of an internally-determined log file.
(Realtime, reads and re-writes the file.)
Also outputs the text block (including any line breaks)
to the console or host.
#>
function LogAndOutput ($textBlock) {
$ps_gimble_LogFile_WriteLineCache = @()
$ps_gimble_LogFile_WriteLineCache += $textBlock
try {
Add-Content $ps_gimble_QualifiedLogfile $ps_gimble_LogFile_WriteLineCache
}
catch {
Write-Host $error
}
Write-Host $textBlock
}