-
Notifications
You must be signed in to change notification settings - Fork 17
/
Umdh-manager.ps1
463 lines (386 loc) · 14.7 KB
/
Umdh-manager.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
<#
.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 : umdh-manager.ps1
Author : jagilber
Version : 150611
.EXAMPLE
.\Umdh-manager.ps1 -action deploy -machine clt-jgs-2k8r2-2 -sourcePath c:\temp\umdh-manager\sourcefiles -destPath admin$\temp
.EXAMPLE
.\Umdh-manager.ps1 -action undeploy -machine clt-jgs-2k8r2-2 -sourcePath c:\temp\umdh-manager\sourcefiles -destPath admin$\temp
.EXAMPLE
.\Umdh-manager.ps1 -action undeploy -machine 127.0.0.1 -sourcePath c:\temp\umdh-manager\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 name to deploy to:")]
[string] $machine,
[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
)
$scriptName = "umdh-script-start.bat"
$logFile = "umdh-manager.log"
$processWaitMs = 1000
$TaskName = "Umdh-manager"
$TaskDescr = "Manages umdh"
$TaskDir = "%systemroot%\temp"
#use svcHostService OR processName but not both
$svcHostService = "WinRM"
$processName = $null #"testlimit64"
$TaskArg = ""
$TaskCommand = "$($TaskDir)\$($scriptName)"
$sleepTimeHours = 1
$requiresRestart = $false
$procDumpExe = "procdump.exe"
$procArguments = "-accepteula -ma"
# ----------------------------------------------------------------------------------------------------------------
function main()
{
runas-admin
if(![string]::IsNullOrEmpty($machine))
{
$isRemote = $true
}
else
{
$machine = [Environment]::MachineName
$isRemote = $false
}
if($action -ieq "deploy")
{
#[Environment]::SetEnvironmentVariable( "_NT_SYMBOL_PATH", "c:\mysymbols;srv*c:\mycache*http://msdl.microsoft.com/download/symbols", [System.EnvironmentVariableTarget]::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
}
# verify $svcHostService is in its own process
if($svcHostService -ne $null)
{
if((get-service -ComputerName $machine -Name $svcHostService).ServiceType -imatch "Win32ShareProcess")
{
$retVal = run-process -processName "sc" -arguments "\\$($machine) config $svcHostService type= own" -wait $true
$svc = Get-Service -Name $svcHostService -ComputerName $machine
$svc.Stop()
$count = 0
while($svc.Status -ine "Stopped" -and $count -lt 30)
{
Start-Sleep 1
$svc = Get-Service -Name $svcHostService -ComputerName $machine
$count++
}
$svc.Start()
log-info "$svcHostService has been configured to run in its own process."
}
else
{
log-info "$svcHostService already set to use its own process"
}
}
# get source files
$sourceFiles = [IO.Directory]::GetFiles($sourcePath, "*.*", [System.IO.SearchOption]::TopDirectoryOnly)
# copy files
foreach($sourceFile in $sourceFiles)
{
$destFile = [IO.Path]::GetFileName($sourceFile)
$destFile = "\\$($machine)\$($destPath)\$($destFile)"
log-info "copying file $($sourceFile) to $($destFile)"
try
{
[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
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
}
elseif($action -ieq "undeploy")
{
if($svcHostService -ne $null)
{
if((get-service -ComputerName $machine -Name $svcHostService).ServiceType -imatch "Win32OwnProcess")
{
$retVal = run-process -processName "sc" -arguments "\\$($machine) config $svcHostService type= share" -wait $true
$svc = Get-Service -Name $svcHostService -ComputerName $machine
$svc.Stop()
$count = 0
while($svc.Status -ine "Stopped" -and $count -lt 30)
{
Start-Sleep 1
$svc = Get-Service -Name $svcHostService -ComputerName $machine
$count++
}
$svc.Start()
log-info "$svcHostService set back to sharing process (default)."
}
else
{
log-info "$svcHostService already set to use share process"
}
}
manage-scheduledTask -enable $false -machine $machine
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
}
# no arguments so do task
set-location $psscriptroot
$workingDir = (get-location).path
$umdhExe = "$($workingDir)\umdh.exe"
if(![System.IO.File]::Exists($umdhExe))
{
log-info "$($umdhExe) does not exist. copy umdh.exe into same directory as script. exiting"
return
}
$procDumpExe = "$($workingDir)\$($procDumpExe)"
if(![System.IO.File]::Exists($procDumpExe))
{
log-info "$($procDumpExe) does not exist. copy umdh.exe into same directory as script. exiting"
return
}
if($svcHostService -ne $null)
{
if((get-service -ComputerName $machine -Name $svcHostService).ServiceType -imatch "Win32ShareProcess")
{
log-info "Error:$svcHostService not configured to run its own process."
log-info "Run script with -action deploy to change. exiting..."
return
}
}
$dumpSchedule = @{100 = $false; 200 = $false; 300 = $false; 400 = $false }
# do work
while($true)
{
$processId = $null
$outputFile = "$($workingdir)\umdh-$([System.DateTime]::Now.ToString(`"yy-MM-dd-HH-mm`")).txt"
if($svcHostService -ne $null)
{
$processId = (gwmi Win32_Service -Filter "Name LIKE '$svcHostService'").ProcessId
}
elseif($processName -ne $null)
{
$processId = (get-process -Name $processName).Id
if([string]::IsNullOrEmpty($processId) -or $processId -lt 1)
{
log-info "Error:$processName does not exist. sleeping..."
if($sleepTimeHours -eq 0)
{
#test mode sleep 1 second
sleep -Seconds 10
}
else
{
sleep -Seconds ($sleepTimeHours * 60 * 60)
}
continue
}
}
$arguments = "-p:$($processId) -f:$($outputFile)"
run-process -processName $umdhExe -arguments $arguments -wait $true
# check size of private bytes
# dump at 100,200,300,400,quit
$process = Get-Process -id $processId
$privateMBytes = $process.PrivateMemorySize / 1024 / 1024
if(($privateMBytes -gt 100) -and ($dumpSchedule[100] -eq $false))
{
$dumpSchedule[100] = $true
run-process -processName $procDumpExe -arguments "$procArguments $processId" -wait $true
}
elseif(($privateMBytes -gt 200) -and ($dumpSchedule[200] -eq $false))
{
$dumpSchedule[200] = $true
run-process -processName $procDumpExe -arguments "$procArguments $processId" -wait $true
}
elseif(($privateMBytes -gt 300) -and ($dumpSchedule[300] -eq $false))
{
$dumpSchedule[300] = $true
run-process -processName $procDumpExe -arguments "$procArguments $processId" -wait $true
}
elseif(($privateMBytes -gt 400) -and ($dumpSchedule[400] -eq $false))
{
$dumpSchedule[400] = $true
run-process -processName $procDumpExe -arguments "$procArguments $processId" -wait $true
return;
}
if($sleepTimeHours -eq 0)
{
#test mode sleep 1 second
sleep -Seconds 10
}
else
{
sleep -Seconds ($sleepTimeHours * 60 * 60)
}
}
}
# ----------------------------------------------------------------------------------------------------------------
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)
{
# win 2k8r2 and below have to use com object
# 2012 can use cmdlets
$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($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
}
}
# ----------------------------------------------------------------------------------------------------------------
main
log-info "finished"