forked from jagilber/powershellScripts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.ps1
647 lines (566 loc) · 20.6 KB
/
functions.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# general functions
<#
.SYNOPSIS
powershell script to manage event logs on multiple machines
.DESCRIPTION
To enable script execution, you may need to Set-ExecutionPolicy Bypass -Force
Copyright 2017 Microsoft Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Requirements:
- administrator powershell prompt
- administrative access to machine
- remote network ports:
- smb 445
- rpc endpoint mapper 135
- rpc ephemeral ports
.NOTES
File Name : functions.ps1
Author : jagilber
Version : 170707.2 finally fix for merge getfiles multiple machines
History :
.EXAMPLE
.\event-log-manager.ps1 -rds -minutes 10
Example command to query rds event logs for last 10 minutes.
.PARAMETER commandCount
modify default value of 1 for number of times to execute command on match.
.LINK
https://gallery.technet.microsoft.com/Windows-Event-Log-ad958986
#>
# proxy test
#$proxyString = "http://127.0.0.1:5555"
#$proxyUri = new-object System.Uri($proxyString)
#[Net.WebRequest]::DefaultWebProxy = new-object System.Net.WebProxy ($proxyUri, $true)
#$proxy = [System.Net.CredentialCache]::DefaultCredentials
#[System.Net.WebRequest]::DefaultWebProxy.Credentials = $proxy
# end proxy test
# auth test
$profileContext = "$($env:TEMP)\ProfileContext.ctx"
# end auth test
function main()
{
try {
authenticate-azureRm
}
catch {
write-warning "main:exception:$($error | out-string)"
}
finally
{
if (test-path $profileContext)
{
Remove-Item -Path $profileContext -Force
}
}
}
# ----------------------------------------------------------------------------------------------------------------
function authenticate-azureRm($context)
{
<#
# 181026 Your Azure credentials have not been set up or have expired, please run Connect-AzureRmAccount to set up your Azure credentials
# https://github.com/Azure/azure-powershell/issues/7456
Clear-AzureRmContext # Thanks to Mark
Disable-AzureRmContextAutosave -Scope Process # Thanks to Mark, but my scope is Process
Import-AzureRmContext -Path $File # Where File is an EMPTY JSON FILE (saved when no context)
Dir "$($Env:Appdata)\Windows Azure Powershell" -Filter "Azure*.json" | Remove-Item -Force
Now you can Import-AzureRMContext yourjsonfile.json
and 4. are only needed for JSON logon, Connect-AzureRMAccount does not need them. probably only one of them is needed. Investigating further.
# fix
Clear-AzureRmContext
Disable-AzureRmContextAutosave -Scope Process
Import-AzureRmContext -Path $emptyJson # Where File is an EMPTY JSON FILE (saved when no context)
# end fix
#>
if ($context)
{
$ctx = $null
$ctx = Import-AzureRmContext -Path $context
# bug to be fixed 8/2017
# From <https://github.com/Azure/azure-powershell/issues/3954>
[void]$ctx.Context.TokenCache.Deserialize($ctx.Context.TokenCache.CacheData)
return $true
}
# make sure at least wmf 5.0 installed
if ($PSVersionTable.PSVersion -lt [version]"5.0.0.0")
{
write-host "update version of powershell to at least wmf 5.0. exiting..." -ForegroundColor Yellow
start-process "https://www.bing.com/search?q=download+windows+management+framework+5.0"
# start-process "https://www.microsoft.com/en-us/download/details.aspx?id=50395"
exit
}
# verify NuGet package
$nuget = get-packageprovider nuget -Force
if (-not $nuget -or ($nuget.Version -lt [version]::New("2.8.5.22")))
{
write-host "installing nuget package..."
install-packageprovider -name NuGet -minimumversion ([version]::New("2.8.5.201")) -force
}
$allModules = (get-module azure* -ListAvailable).Name
# install AzureRM module
if ($allModules -inotcontains "AzureRM")
{
# each has different azurerm module requirements
# installing azurerm slowest but complete method
# if wanting to do minimum install, run the following script against script being deployed
# https://raw.githubusercontent.com/jagilber/powershellScripts/master/script-azurerm-module-enumerator.ps1
# this will parse scripts in given directory and output which azure modules are needed to populate the below
# at least need profile, resources, insights, logicapp for this script
if ($allModules -inotcontains "AzureRM.profile")
{
write-host "installing AzureRm.profile powershell module..."
install-module AzureRM.profile -force
}
if ($allModules -inotcontains "AzureRM.resources")
{
write-host "installing AzureRm.resources powershell module..."
install-module AzureRM.resources -force
}
if ($allModules -inotcontains "AzureRM.compute")
{
write-host "installing AzureRm.compute powershell module..."
install-module AzureRM.compute -force
}
if ($allModules -inotcontains "AzureRM.network")
{
write-host "installing AzureRm.network powershell module..."
install-module AzureRM.network -force
}
Import-Module azurerm.profile
Import-Module azurerm.resources
Import-Module azurerm.compute
Import-Module azurerm.network
#write-host "installing AzureRm powershell module..."
#install-module AzureRM -force
}
else
{
Import-Module azurerm
}
# authenticate
try
{
$tenants = @(Get-AzureRmTenant)
if ($tenants)
{
write-host "auth passed $($tenants.Count)"
}
else
{
write-host "auth error $($error)" -ForegroundColor Yellow
throw [Exception]
}
}
catch
{
if(!(connect-azurermaccount))
{
log-info "exception authenticating. exiting $($error | out-string)" -ForegroundColor Yellow
exit 1
}
}
#main:
#$profileContext = "$($env:TEMP)\ProfileContext.ctx"
Save-AzureRmContext -Path $profileContext -Force
#main finally
#finally
#{
#if(test-path $profileContext)
#{
# Remove-Item -Path $profileContext -Force
#}
#}
#background job for bug https://github.com/Azure/azure-powershell/issues/7110
#Disable-AzureRmContextAutosave -scope Process -ErrorAction SilentlyContinue | Out-Null
}
# ----------------------------------------------------------------------------------------------------------------
function get-subscriptions()
{
write-host "enumerating subscriptions"
$subList = @{}
$subs = Get-AzureRmSubscription -WarningAction SilentlyContinue
$newSubFormat = (get-module AzureRM.Resources).Version.ToString() -ge "4.0.0"
if ($subs.Count -gt 1)
{
[int]$count = 1
foreach ($sub in $subs)
{
if ($newSubFormat)
{
$message = "$($count). $($sub.name) $($sub.id)"
$id = $sub.id
}
else
{
$message = "$($count). $($sub.SubscriptionName) $($sub.SubscriptionId)"
$id = $sub.SubscriptionId
}
Write-Host $message
[void]$subList.Add($count, $id)
$count++
}
[int]$id = Read-Host ("Enter number for subscription to enumerate or {enter} to query all:")
$null = Set-AzureRmContext -SubscriptionId $subList[$id].ToString()
if ($id -ne 0 -and $id -le $subs.count)
{
return $subList[$id]
}
}
elseif ($subs.Count -eq 1)
{
if ($newSubFormat)
{
[void]$subList.Add("1", $subs.Id)
}
else
{
[void]$subList.Add("1", $subs.SubscriptionId)
}
}
write-verbose "get-subscriptions returning:$($subs | format-list | out-string)"
return $subList.Values
}
# ----------------------------------------------------------------------------------------------------------------
function get-sysInternalsUtility ([string] $utilityName)
{
try
{
$destFile = "$(get-location)\$utilityName"
[System.Net.ServicePointManager]::Expect100Continue = $true;
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
if (![IO.File]::Exists($destFile))
{
$sysUrl = "https://live.sysinternals.com/$($utilityName)"
write-host "Sysinternals process $($utilityName) is needed for this option!" -ForegroundColor Yellow
if ((read-host "Is it ok to download $($sysUrl) ?[y:n]").ToLower().Contains('y'))
{
$webClient = new-object System.Net.WebClient
$webclient.UseDefaultCredentials = $true
#$webclient.Credentials = [Net.NetworkCredential](get-credential -UserName "$($env:USERDOMAIN)\$($env:USERNAME)" -Message "AZRDAV Sharepoint")
[void]$webClient.DownloadFile($sysUrl, $destFile)
log-info "sysinternals utility $($utilityName) downloaded to $($destFile)"
}
else
{
return [string]::Empty
}
}
return $destFile
}
catch
{
log-info "Exception downloading $($utilityName): $($error)"
$error.Clear()
return [string]::Empty
}
}
$updateUrl = "https://raw.githubusercontent.com/jagilber/powershellScripts/master/rds-lic-svr-chk.ps1"
# ----------------------------------------------------------------------------------------------------------------
function get-update($updateUrl, $destinationFile)
{
log-info "get-update:checking for updated script: $($updateUrl)"
$file = ""
$git = $null
try
{
$git = Invoke-RestMethod -UseBasicParsing -Method Get -Uri $updateUrl
# git may not have carriage return
# reset by setting all to just lf
$git = [regex]::Replace($git, "`r`n","`n")
# add cr back
$git = [regex]::Replace($git, "`n", "`r`n")
if ([IO.File]::Exists($destinationFile))
{
$file = [IO.File]::ReadAllText($destinationFile)
}
if (([string]::Compare($git, $file) -ne 0))
{
log-info "copying script $($destinationFile)"
[IO.File]::WriteAllText($destinationFile, $git)
return $true
}
else
{
log-info "script is up to date"
}
return $false
}
catch [System.Exception]
{
log-info "get-update:exception: $($error)"
$error.Clear()
return $false
}
}
# ----------------------------------------------------------------------------------------------------------------
function log-info($data)
{
$dataWritten = $false
$data = "$([System.DateTime]::Now):$($data)`n"
if ([regex]::IsMatch($data.ToLower(), "error|exception|fail|warning"))
{
write-host $data -foregroundcolor Yellow
}
elseif ([regex]::IsMatch($data.ToLower(), "running"))
{
write-host $data -foregroundcolor Green
}
elseif ([regex]::IsMatch($data.ToLower(), "job completed"))
{
write-host $data -foregroundcolor Cyan
}
elseif ([regex]::IsMatch($data.ToLower(), "starting"))
{
write-host $data -foregroundcolor Magenta
}
else
{
Write-Host $data
}
$counter = 0
while (!$dataWritten -and $counter -lt 1000)
{
try
{
$ret = out-file -Append -InputObject $data -FilePath $logFile
$dataWritten = $true
}
catch
{
Start-Sleep -Milliseconds 50
$error.Clear()
$counter++
}
}
}
$HKCR = 2147483648 #HKEY_CLASSES_ROOT
$HKCU = 2147483649 #HKEY_CURRENT_USER
$HKLM = 2147483650 #HKEY_LOCAL_MACHINE
$HKUS = 2147483651 #HKEY_USERS
$HKCC = 2147483653 #HKEY_CURRENT_CONFIG
# ----------------------------------------------------------------------------------------------------------------
function read-reg($machine, $hive, $key, $value, $subKeySearch = $true)
{
$retVal = new-object Text.StringBuilder
if ([string]::IsNullOrEmpty($value))
{
[void]$retVal.AppendLine("-----------------------------------------")
[void]$retVal.AppendLine("enumerating $($key)")
$enumValue = $false
}
else
{
[void]$retVal.AppendLine("-----------------------------------------")
[void]$retVal.AppendLine("enumerating $($key) for value $($value)")
$enumValue = $true
}
try
{
$reg = [wmiclass]"\\$($machine)\root\default:StdRegprov"
$sNames = $reg.EnumValues($hive, $key).sNames
$sTypes = $reg.EnumValues($hive, $key).Types
for ($i = 0; $i -lt $sNames.count; $i++)
{
if (![string]::IsNullOrEmpty($value) -and $sNames[$i] -inotlike $value)
{
continue
}
switch ($sTypes[$i])
{
# REG_SZ
1
{
$keyValue = $reg.GetStringValue($hive, $key, $sNames[$i]).sValue
if ($enumValue)
{
return $keyValue
}
else
{
[void]$retval.AppendLine("$($sNames[$i]):$($keyValue)")
}
}
# REG_EXPAND_SZ
2
{
$keyValue = $reg.GetExpandStringValue($hive, $key, $sNames[$i]).sValue
if ($enumValue)
{
return $keyValue
}
else
{
[void]$retval.AppendLine("$($sNames[$i]):$($keyValue)")
}
}
# REG_BINARY
3
{
$keyValue = (($reg.GetBinaryValue($hive, $key, $sNames[$i]).uValue) -join ',')
if ($enumValue -or $displayBinaryBlob)
{
return $keyValue
}
elseif ($displayBinaryBlob)
{
[void]$retval.AppendLine("$($sNames[$i]):$($keyValue)")
}
else
{
$blob = $reg.GetBinaryValue($hive, $key, $sNames[$i]).uValue
[void]$retval.AppendLine("$($sNames[$i]):(Binary Blob (length:$($blob.Length)))")
}
}
# REG_DWORD
4
{
$keyValue = $reg.GetDWORDValue($hive, $key, $sNames[$i]).uValue
if ($enumValue)
{
return $keyValue
}
else
{
[void]$retval.AppendLine("$($sNames[$i]):$($keyValue)")
}
}
# REG_MULTI_SZ
7
{
$keyValue = (($reg.GetMultiStringValue($hive, $key, $sNames[$i]).sValue) -join ',')
if ($enumValue)
{
return $keyValue
}
else
{
[void]$retval.AppendLine("$($sNames[$i]):$($keyValue)")
}
}
# REG_QWORD
11
{
$keyValue = $reg.GetQWORDValue($hive, $key, $sNames[$i]).uValue
if ($enumValue)
{
return $keyValue
}
else
{
[void]$retval.AppendLine("$($sNames[$i]):$($keyValue)")
}
}
# ERROR
default { [void]$retval.AppendLine("unknown type") }
}
}
if ([string]::IsNullOrEmpty($value) -and $subKeySearch)
{
foreach ($subKey in $reg.EnumKey($hive, $key).sNames)
{
if ([string]::IsNullOrEmpty($subKey))
{
continue
}
read-reg -machine $machine -hive $hive -key "$($key)\$($subkey)"
}
}
if ($enumValue)
{
# no value
return $null
}
else
{
return $retVal.ToString()
}
}
catch
{
#"read-reg:exception $($error)"
$error.Clear()
return
}
}
# ----------------------------------------------------------------------------------------------------------------
function runas-admin()
{
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "please restart script in administrator powershell session. exiting..."
return $false
}
return $true
}
# ----------------------------------------------------------------------------------------------------------------
$noretry
# ----------------------------------------------------------------------------------------------------------------
function runas-admin()
{
write-verbose "checking for admin"
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
if (!$noretry)
{
write-host "restarting script as administrator."
Write-Host "run-process -processName powershell.exe -arguments -ExecutionPolicy Bypass -File $($SCRIPT:MyInvocation.MyCommand.Path) -noretry"
run-process -processName "powershell.exe" -arguments "-ExecutionPolicy Bypass -File $($SCRIPT:MyInvocation.MyCommand.Path) -noretry" -wait $true
}
return $false
}
else
{
write-verbose "running as admin"
}
return $true
}
# ----------------------------------------------------------------------------------------------------------------
function run-process([string] $processName, [string] $arguments, [switch] $wait = $false)
{
$Error.Clear()
log-info "Running process $processName $arguments"
$exitVal = 0
$process = New-Object Diagnostics.Process
$process.StartInfo.UseShellExecute = !$wait
$process.StartInfo.RedirectStandardOutput = $wait
$process.StartInfo.RedirectStandardError = $wait
$process.StartInfo.FileName = $processName
$process.StartInfo.Arguments = $arguments
$process.StartInfo.CreateNoWindow = $wait
$process.StartInfo.WorkingDirectory = get-location
$process.StartInfo.ErrorDialog = $true
$process.StartInfo.ErrorDialogParentHandle = ([Diagnostics.Process]::GetCurrentProcess()).Handle
$process.StartInfo.LoadUserProfile = $false
$process.StartInfo.WindowStyle = [Diagnostics.ProcessWindowstyle]::Normal
[void]$process.Start()
if ($wait -and !$process.HasExited)
{
if ($process.StandardOutput.Peek() -gt -1)
{
$stdOut = $process.StandardOutput.ReadToEnd()
log-info $stdOut
}
if ($process.StandardError.Peek() -gt -1)
{
$stdErr = $process.StandardError.ReadToEnd()
log-info $stdErr
$Error.Clear()
}
}
elseif ($wait)
{
log-info "Error:Process ended before capturing output."
}
$exitVal = $process.ExitCode
log-info "Running process exit $($processName) : $($exitVal)"
$Error.Clear()
return $stdOut
}
# ----------------------------------------------------------------------------------------------------------------
main