forked from jagilber/powershellScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deploy-files-task.ps1
479 lines (389 loc) · 14.7 KB
/
deploy-files-task.ps1
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
<#
.SYNOPSIS
powershell script to manage umdh on local or remote machine
.DESCRIPTION
This script will help with the deployment and undeployment of umdh across multiple machines.
note: when undeploying, the powershell process will continue to run on remote machine until server is rebooted
- umdh files will be in the remote server share that was specified. in examples below would be %systemroot%\temp
.NOTES
File Name : deploy-files-task.ps1
Author : jagilber
Version : 150824
.EXAMPLE
.\deploy-files-task.ps1 -action deploy -machine clt-jgs-2k8r2-2 -sourcePath c:\temp\deploy-files-task\sourcefiles -destPath admin$\temp
.EXAMPLE
.\deploy-files-task.ps1 -action undeploy -machine clt-jgs-2k8r2-2 -sourcePath c:\temp\deploy-files-task\sourcefiles -destPath admin$\temp
.EXAMPLE
.\deploy-files-task.ps1 -action undeploy -machine 127.0.0.1 -sourcePath c:\temp\deploy-files-task\sourcefiles -destPath admin$\temp
.PARAMETER action
The action to take. Currently this is either 'deploy' or 'undeploy'.
.PARAMETER machine
The remote machine to deploy to. if deploying to local machine do not use this argument.
#>
Param(
[parameter(Position=0,Mandatory=$false,HelpMessage="Enter the action to take: [deploy|undeploy]")]
[string] $action,
[parameter(Position=1,Mandatory=$false,HelpMessage="Enter machine names to deploy to:")]
[string[]] $machines,
[parameter(Position=2,Mandatory=$false,HelpMessage="Enter source folder containing files. example: c:\temp\sourcefiles")]
[string] $sourcePath,
[parameter(Position=3,Mandatory=$false,HelpMessage='Enter relative destination share path folder containing files. example: admin$\temp')]
[string] $destPath="admin`$\temp",
[parameter(Position=4,Mandatory=$false,HelpMessage='Enter DOS style *.* file pattern for files to gather from remote destination path. example: *.pml')]
[string] $gatherFilePattern = "*.pml",
[parameter(Position=5,Mandatory=$false,HelpMessage='Enter full path to folder where to store gathered files')]
[string] $gatherPath = "$(get-location)\gather"
)
$logFile = "deploy-files-task.log"
$processWaitMs = 1000
# scheduled task info
$taskInfoDeploy = @{}
$taskInfoDeploy.Add("taskname","EventLog Monitor deploy")
$taskInfoDeploy.Add("taskdescr","Monitors eventlog for event")
$taskInfoDeploy.Add("taskcommand","powershell.exe")
$taskInfoDeploy.Add("taskdir","%systemroot%\temp")
$taskInfoDeploy.Add("taskarg","-WindowStyle Hidden -NonInteractive -Executionpolicy bypass -file %systemroot%\temp\event-task-procmon.ps1")
$taskInfoUnDeploy = @{}
$taskInfoUnDeploy.Add("taskname","EventLog Monitor undeploy")
$taskInfoUnDeploy.Add("taskdescr","removes Monitors eventlog for event")
$taskInfoUnDeploy.Add("taskcommand","powershell.exe")
$taskInfoUnDeploy.Add("taskdir","%systemroot%\temp")
$taskInfoUnDeploy.Add("taskarg","-WindowStyle Hidden -NonInteractive -Executionpolicy bypass -file %systemroot%\temp\event-task-procmon.ps1 -terminate")
$time = (get-date) #- (new-timespan -day 12)
$requiresRestart = $false
# ----------------------------------------------------------------------------------------------------------------
function main()
{
runas-admin
if(![string]::IsNullOrEmpty($machines))
{
$isRemote = $true
}
else
{
$machines = [Environment]::MachineName
$isRemote = $false
}
if($machines.Length -eq 1 -and $machines[0].Contains(","))
{
$machines = $machines.Split(",")
}
foreach($machine in $machines)
{
if(!(test-path "\\$($machine)\$($destPath)"))
{
log-info "unable to connect to $($machine). skipping."
continue
}
if($action -ieq "deploy")
{
deploy-files -machine $machine
}
elseif($action -ieq "undeploy")
{
undeploy-files -machine $machine
}
}
}
# ----------------------------------------------------------------------------------------------------------------
function run-process([string] $processName, [string] $arguments, [bool] $wait = $false)
{
log-info "Running process $processName $arguments"
$exitVal = 0
$process = New-Object System.Diagnostics.Process
$process.StartInfo.UseShellExecute = $false
$process.StartInfo.RedirectStandardOutput = $true
$process.StartInfo.RedirectStandardError = $true
$process.StartInfo.FileName = $processName
$process.StartInfo.Arguments = $arguments
$process.StartInfo.CreateNoWindow = $true
#only needed if useshellexecute is true
$process.StartInfo.WorkingDirectory = get-location #$workingDirectory
[void]$process.Start()
if($wait -and !$process.HasExited)
{
$process.WaitForExit($processWaitMs)
$exitVal = $process.ExitCode
$stdOut = $process.StandardOutput.ReadToEnd()
$stdErr = $process.StandardError.ReadToEnd()
log-info "Process output:$stdOut"
if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0")
{
log-info "Error:$stdErr `n $Error"
$Error.Clear()
}
}
elseif($wait)
{
log-info "Process ended before capturing output."
}
#return $exitVal
return $stdOut
}
# ----------------------------------------------------------------------------------------------------------------
function log-info($data)
{
$data = "$([System.DateTime]::Now):$($data)`n"
Write-Host $data
out-file -Append -InputObject $data -FilePath $logFile
}
# ----------------------------------------------------------------------------------------------------------------
function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [bool] $wait = $false)
{
# win 2k8r2 and below have to use com object
# 2012 can use cmdlets
$TaskName = $taskInfo.taskname
$TaskDescr = $taskInfo.taskdescr
$TaskCommand = $taskInfo.taskcommand
$TaskDir = $taskInfo.taskdir
$TaskArg = $taskInfo.taskarg
$error.Clear()
$service = new-object -ComObject("Schedule.Service")
# connect to the local machine.
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx
# for remote machine connect do $service.Connect(serverName,user,domain,password)
if([string]::IsNullOrEmpty($machine))
{
$service.Connect()
}
else
{
$service.Connect($machine)
}
$rootFolder = $service.GetFolder("\")
if($enable)
{
$TaskDefinition = $service.NewTask(0)
$TaskDefinition.RegistrationInfo.Description = "$TaskDescr"
# 2k8r2 is 65539 (0x10003) 1.3
# procmon needs at least 2k8r2 compat
#$TaskDefinition.Settings.Compatibility = 3
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true
$triggers = $TaskDefinition.Triggers
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx
$trigger = $triggers.Create(8) # Creates a "boot time" trigger
#$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
$trigger.Enabled = $true
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx
$Action = $TaskDefinition.Actions.Create(0)
$action.Path = "$TaskCommand"
$action.Arguments = "$TaskArg"
$action.WorkingDirectory = $TaskDir
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx
$rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5)
#start task
$task = $rootFolder.GetTask($TaskName)
$task.Run($null)
}
else
{
# stop task if its running
foreach($task in $service.GetRunningTasks(1))
{
if($task.Name -ieq $TaskName)
{
log-info "found task"
$task.Stop()
}
}
# delete task
$rootFolder.DeleteTask($TaskName,$null)
}
if($wait)
{
log-info "waiting for task to complete"
while($true)
{
$foundTask = $false
# stop task if its running
foreach($task in $service.GetRunningTasks(1))
{
if($task.Name -ieq $TaskName)
{
log-info "found task"
$foundTask = $true
}
}
if(!$foundTask)
{
break
}
Start-Sleep -Seconds 5
}
}
if($error.Count -ge 1)
{
log-info $error
$error.Clear()
return $false
}
else
{
return $true
}
}
# ----------------------------------------------------------------------------------------------------------------
function runas-admin([string] $arguments)
{
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( `
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{
log-info "please restart script as administrator. exiting..."
exit
}
}
# ----------------------------------------------------------------------------------------------------------------
function deploy-files($machine)
{
if(![IO.Directory]::Exists($sourcePath))
{
log-info "unable to find source path $($sourcePath). exiting"
return
}
if(![IO.Directory]::Exists("\\127.0.0.1\$($destPath)"))
{
log-info "unable to determine destination path \\127.0.0.1\$($destPath). exiting"
return
}
# get source files
$sourceFiles = [IO.Directory]::GetFiles($sourcePath, "*.*", [System.IO.SearchOption]::AllDirectories)
# copy files
foreach($sourceFile in $sourceFiles)
{
#$destFile = [IO.Path]::GetFileName($sourceFile)
$destFile = $sourceFile.Replace("$($sourcePath)\","")
$destFile = "\\$($machine)\$($destPath)\$($destFile)"
log-info "copying file $($sourceFile) to $($destFile)"
try
{
if(![IO.Directory]::Exists([IO.Path]::GetDirectoryName($destFile)))
{
[IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($destFile))
}
[IO.File]::Copy($sourceFile, $destFile, $true)
}
catch
{
log-info "Exception:Copying File:$($sourceFile) to $($destFile): $($Error)"
$Error.Clear()
}
}
#create scheduled task
manage-scheduledTask -enable $true -machine $machine -taskInfo $taskInfoDeploy
if($requiresRestart)
{
$retVal = Read-Host -Prompt "server needs to be restarted. Do you want to do this now? [yes|no]"
if(![regex]::IsMatch($retVal,"yes",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase))
{
log-info "exiting script. server not restarted"
}
else
{
log-info "restarting server."
Restart-Computer -ComputerName $machine -Force -Impersonation Impersonate
}
}
return
}
# ----------------------------------------------------------------------------------------------------------------
function undeploy-files($machine)
{
manage-scheduledTask -enable $false -machine $machine -taskInfo $taskInfoDeploy
manage-scheduledTask -enable $true -machine $machine -taskInfo $taskInfoUnDeploy -wait $true
manage-scheduledTask -enable $false -machine $machine -taskInfo $taskInfoUnDeploy
if(![string]::IsNullOrEmpty($gatherFilePattern))
{
$remotePath = "\\$($machine)\$($destPath)"
# get remote files
$directoryInfo = new-object IO.DirectoryInfo ($remotePath)
[IO.FileInfo[]] $sourceFiles = ($directoryInfo.EnumerateFiles($gatherFilePattern,[IO.SearchOption]::TopDirectoryOnly))
# copy files
foreach($sourceFile in $sourceFiles)
{
$count = 0
while ($count -lt 1000)
{
if(is-fileLocked($sourceFile.FullName))
{
log-info "source file in use: $($sourceFile.FullName)"
Start-Sleep -Seconds 1
$count++
}
else
{
$count = 0
break
}
}
if($count -ne 0)
{
continue
}
$destFile = $sourceFile.FullName.Replace("$($remotePath)\","")
$destFileBase = [IO.Path]::GetFileNameWithoutExtension($destFile)
$destFileExtension = [IO.Path]::GetExtension($destFile)
$destFile = "$($destFileBase)-$($sourceFile.CreationTime.ToString("yy-MM-dd-hh-mm-ss"))$($destFileExtension)"
$destFile = "$($gatherPath)\$($machine)\$($destFile)"
log-info "copying file $($sourceFile.FullName) to $($destFile)"
try
{
if(![IO.Directory]::Exists([IO.Path]::GetDirectoryName($destFile)))
{
[IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($destFile))
}
[IO.File]::Copy($sourceFile.FullName, $destFile, $true)
[IO.File]::Delete($sourceFile.FullName)
}
catch
{
log-info "Exception:Copying File:$($sourceFile.FullName) to $($destFile): $($Error)"
$Error.Clear()
}
}
}
if($requiresRestart)
{
$retVal = Read-Host -Prompt "server needs to be restarted. Do you want to do this now? [yes|no]"
if(![regex]::IsMatch($retVal,"yes",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase))
{
log-info "exiting script. server not restarted"
}
else
{
log-info "restarting server."
Restart-Computer -ComputerName $machine -Force -Impersonation Impersonate
}
}
return
}
# ----------------------------------------------------------------------------------------------------------------
function is-fileLocked([string] $file)
{
$fileInfo = New-Object System.IO.FileInfo $file
if ((Test-Path -Path $file) -eq $false)
{
log-info "File does not exist:$($file)"
return $false
}
try
{
$fileStream = $fileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
if ($fileStream)
{
$fileStream.Close()
}
log-info "File is NOT locked:$($file)"
return $false
}
catch
{
# file is locked by a process.
log-info "File is locked:$($file)"
return $true
}
}
# ----------------------------------------------------------------------------------------------------------------
main
log-info "finished"