-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslr.psm1
1593 lines (1397 loc) · 54.8 KB
/
slr.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
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#########################
#region Logging functions
#########################
Function Log-Start{
<#
.SYNOPSIS
Creates log file
.DESCRIPTION
Creates log file with path and name that is passed. Checks if log file exists, and if it does - moves it to directory oldlogs and creates a new one. Delete logfiles in oldlogs which are older than 7 days
Once created, writes initial logging data
.PARAMETER LogPath
Mandatory. Path of where log is to be created. Example: C:\Windows\Temp
.PARAMETER LogName
Mandatory. Name of log file to be created. Example: Test_Script.log
.PARAMETER ScriptVersion
Mandatory. Version of the running script which will be written in the log. Example: 1.5
.INPUTS
Parameters above
.OUTPUTS
Log file created
.NOTES
Version: 1.0
Author: Luca Sturlese
Creation Date: 10/05/12
Purpose/Change: Initial function development
Version: 1.1
Author: Luca Sturlese
Creation Date: 19/05/12
Purpose/Change: Added debug mode support
Version: 1.2
Author: Stephan Liebner
Creation Date: 24/11/15
Purpose/Change: comment line to remove old logs, add line to move old logs to oldlogs directory, change datetime settings from $([DateTime]::Now) to get-date -format "d.M.yyyy HH:mm:ss"
Version: 1.3
Author: Stephan Liebner
Creation Date: 14/12/15
Purpose/Change: checks if logfiles are more than 7 days old from script and delete the oldest
.EXAMPLE
Log-Start -LogPath "C:\Windows\Temp" -LogName "Test_Script.log" -ScriptVersion "1.5"
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][string]$LogPath,
[Parameter(Mandatory=$true)][string]$LogName,
[Parameter(Mandatory=$true)][string]$ScriptVersion)
Process{
#Build fullpath to logfile
$LogFullPath = Join-Path -Path $LogPath -ChildPath $LogName
#Folder in script directory for old log files
$OldLogPath = $LogPath + "\" + "oldlogs"
#################################################
#Check if directory oldlogs exist, else create it
#################################################
If((Test-Path -Path $OldLogPath))
{
#Check if Logfile exist
if (Test-Path -Path $LogFullPath)
{
#Find logfile and move it to oldlogs
Get-ChildItem $LogFullPath | Move-Item -destination $OldLogPath
#Build full path to old logfile for renaming
$FullOldLogPath=Join-Path -Path $OldLogPath -ChildPath $LogName
#Rename file and add file last access time in front (creation time did not work due to filesystem tunneling)
[string]$CreationTime=(Get-ChildItem -Path $OldLogPath -File $LogName).LastAccessTime.ToString('d-M-yyyy_HH-mm-ss')
$NewLogName=$CreationTime+"_"+$LogName
#Check if logfile exist in oldlogs and rename it
if (Test-Path -Path $FullOldLogPath)
{
Rename-Item $FullOldLogPath $NewLogName
}
else {}
}
else {}
}
else
{
#Create oldlogs directory
$NewDir = New-Item $OldLogPath -type directory
#Check if Logfile exist
if (Test-Path -Path $LogFullPath)
{
#Find logfile and move it to oldlogs
Get-ChildItem $LogFullPath | Move-Item -destination $OldLogPath
#Build full path to old logfile for renaming
$FullOldLogPath=Join-Path -Path $OldLogPath -ChildPath $LogName
#Rename file and add file last access time in front (creation time did not work due to filesystem tunneling)
[string]$CreationTime=(Get-ChildItem -Path $OldLogPath -File $LogName).LastAccessTime.ToString('d-M-yyyy_HH-mm-ss')
$NewLogName=$CreationTime+"_"+$LogName
#Check if logfile exist in oldlogs and rename it
if (Test-Path -Path $FullOldLogPath)
{
Rename-Item $FullOldLogPath $NewLogName}
else {}
}
else {}
}
##################################################################
#Checks if logfiles are more than 7 days old and delete the oldest
##################################################################
$Limit=(Get-Date).AddDays(-7)
Get-ChildItem $OldLogPath -Filter *.log| Where-Object {$_.Name -like "*$LogName*" -and $_.LastWriteTime -lt $Limit} | Remove-Item -Force
#####################################
#Create new logfile and start logging
#####################################
$NewLogFile = New-Item -Path $LogPath -Name $LogName -ItemType File
Add-Content -Path $LogFullPath -Value "========================================================================================================="
Add-Content -Path $LogFullPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [START] Starting Log. Running script version [$ScriptVersion]."
Add-Content -Path $LogFullPath -Value "========================================================================================================="
###############################
#Write to screen for debug mode
###############################
write-debug "========================================================================================================="
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [START] Starting Log. Running script version [$ScriptVersion]."
write-debug "========================================================================================================="
}
}
Function Log-Write{
<#
.SYNOPSIS
Writes to a log file
.DESCRIPTION
Appends a new line to the end of the specified log file
.PARAMETER LogPath
Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log
.PARAMETER LineValue
Mandatory. The string that you want to write to the log
.INPUTS
Parameters above
.OUTPUTS
None
.NOTES
Version: 1.0
Author: Luca Sturlese
Creation Date: 10/05/12
Purpose/Change: Initial function development
Version: 1.1
Author: Luca Sturlese
Creation Date: 19/05/12
Purpose/Change: Added debug mode support
.EXAMPLE
Log-Write -LogPath "C:\Windows\Temp\Test_Script.log" -LineValue "This is a new line which I am appending to the end of the log file."
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][string]$LogPath,
[Parameter(Mandatory=$true)][string]$LineValue
)
Process{
#####################################
#Write to logfile
#####################################
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [INFO] $LineValue"
###############################
#Write to screen for debug mode
###############################
write-host "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [INFO] $LineValue"
}
}
Function Log-Warning{
<#
.SYNOPSIS
Writes an warning to a log file
.DESCRIPTION
Writes the passed error to a new line at the end of the specified log file
.PARAMETER LogPath
Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log
.PARAMETER ErrorDesc
Mandatory. The description of the error you want to pass (use $Error[0] for the last error in the error record)
.INPUTS
Parameters above
.OUTPUTS
None
.NOTES
Version: 1.0
Author: Luca Sturlese
Creation Date: 10/05/12
Purpose/Change: Initial function development
Version: 1.1
Author: Luca Sturlese
Creation Date: 19/05/12
Purpose/Change: Added debug mode support. Added -ExitGracefully parameter functionality
Version: 1.2
Author: Stephan Liebner
Creation Date: 27/12/15
Purpose/Change: change the way of displaying errors and accept errors
.EXAMPLE
Log-Warning -LogPath "C:\Windows\Temp\Test_Script.log" -ErrorDesc $_.Exception -ExitGracefully $True
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][string]$LogPath,
#[Parameter(Mandatory=$true)][string]$LineValue,
[Parameter(Mandatory=$true)]$ErrorDesc)
#,
#[Parameter(Mandatory=$true)]$ErrorDesc)
Process{
###################################
#Define variables for error logging
###################################
$ErrorSev=$ErrorDesc.Exception.Severity
$ErrorID=$ErrorDesc.FullyQualifiedErrorId
$ErrorExcep=$ErrorDesc.Exception.Message
$ErrorCom=$ErrorDesc.InvocationInfo.MyCommand.Name
$ErrorScp=$ErrorDesc.InvocationInfo.ScriptName
$ErrorLn=$ErrorDesc.InvocationInfo.ScriptLineNumber
$ErrorOLn=$ErrorDesc.InvocationInfo.OffsetInLine
#####################################
#Write error to logfile
#####################################
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [WARNING] Error Severity: $ErrorSev"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [WARNING] Error FullyQualifiedErrorId: $ErrorID"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [WARNING] Error Message: $ErrorExcep"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [WARNING] Error in CMDlet: $ErrorCom"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [WARNING] Error in ScriptName: $ErrorScp"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [WARNING] Error in ScriptLineNumber: $ErrorLn"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [WARNING] Error in OffsetInLine: $ErrorOLn"
Add-Content -Path $LogPath -Value ""
###############################
#Write to screen for debug mode
###############################
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error Severity: $ErrorSev"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error FullyQualifiedErrorId: $ErrorID"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error Message: $ErrorExcep"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error in CMDlet: $ErrorCom"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error in ScriptName: $ErrorScp"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error in ScriptLineNumber: $ErrorLn"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error in OffsetInLine: $ErrorOLn"
}
}
Function Log-Error{
<#
.SYNOPSIS
Writes an error to a log file
.DESCRIPTION
Writes the passed error to a new line at the end of the specified log file
.PARAMETER LogPath
Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log
.PARAMETER ErrorDesc
Mandatory. The description of the error you want to pass (use $Error[0] for the last error in the error record)
.INPUTS
Parameters above
.OUTPUTS
None
.NOTES
Version: 1.0
Author: Luca Sturlese
Creation Date: 10/05/12
Purpose/Change: Initial function development
Version: 1.1
Author: Luca Sturlese
Creation Date: 19/05/12
Purpose/Change: Added debug mode support. Added -ExitGracefully parameter functionality
Version: 1.2
Author: Stephan Liebner
Creation Date: 27/12/15
Purpose/Change: change the way of displaying errors and accept errors
.EXAMPLE
Log-Error -LogPath "C:\Windows\Temp\Test_Script.log" -ErrorDesc $_.Exception -ExitGracefully $True
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][string]$LogPath,
[Parameter(Mandatory=$true)]$ErrorDesc)
Process{
###################################
#Define variables for error logging
###################################
$ErrorSev=$ErrorDesc.Exception.Severity
$ErrorID=$ErrorDesc.FullyQualifiedErrorId
$ErrorExcep=$ErrorDesc.Exception.Message
$ErrorCom=$ErrorDesc.InvocationInfo.MyCommand.Name
$ErrorScp=$ErrorDesc.InvocationInfo.ScriptName
$ErrorLn=$ErrorDesc.InvocationInfo.ScriptLineNumber
$ErrorOLn=$ErrorDesc.InvocationInfo.OffsetInLine
#####################################
#Write error to logfile
#####################################
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [ERROR] Error Severity: $ErrorSev"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [ERROR] Error FullyQualifiedErrorId: $ErrorID"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [ERROR] Error Message: $ErrorExcep"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [ERROR] Error in CMDlet: $ErrorCom"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [ERROR] Error in ScriptName: $ErrorScp"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [ERROR] Error in ScriptLineNumber: $ErrorLn"
Add-Content -Path $LogPath -Value ""
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [ERROR] Error in OffsetInLine: $ErrorOLn"
Add-Content -Path $LogPath -Value ""
###############################
#Write to screen for debug mode
###############################
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error Severity: $ErrorSev"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error FullyQualifiedErrorId: $ErrorID"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error Message: $ErrorExcep"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error in CMDlet: $ErrorCom"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error in ScriptName: $ErrorScp"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error in ScriptLineNumber: $ErrorLn"
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] Error in OffsetInLine: $ErrorOLn"
}
}
Function Log-Finish{
<#
.SYNOPSIS
Write closing logging data & exit
.DESCRIPTION
Writes finishing logging data to specified log and then exits the calling script
.PARAMETER LogPath
Mandatory. Full path of the log file you want to write finishing data to. Example: C:\Windows\Temp\Test_Script.log
.INPUTS
Parameters above
.OUTPUTS
None
.NOTES
Version: 1.0
Author: Luca Sturlese
Creation Date: 10/05/12
Purpose/Change: Initial function development
Version: 1.1
Author: Luca Sturlese
Creation Date: 19/05/12
Purpose/Change: Added debug mode support
.EXAMPLE
Log-Finish -LogPath "C:\Windows\Temp\Test_Script.log"
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][string]$LogPath
)
Process{
#####################################
#Finish logfile
#####################################
Add-Content -Path $LogPath -Value "========================================================================================================="
Add-Content -Path $LogPath -Value "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [FINISH] Stopping log"
Add-Content -Path $LogPath -Value "========================================================================================================="
###############################
#Write to screen for debug mode
###############################
write-debug "========================================================================================================="
write-debug "[$(get-date -format 'd.M.yyyy HH:mm:ss')] [FINISH] Stopping log"
write-debug "========================================================================================================="
}
}
Function Log-Email{
<#
.SYNOPSIS
Emails log file to list of recipients
.DESCRIPTION
Emails the contents of the specified log file to a list of recipients
.PARAMETER LogPath
Mandatory. Full path of the log file you want to email. Example: C:\Windows\Temp\Test_Script.log
.PARAMETER EmailFrom
Mandatory. The email addresses of who you want to send the email from. Example: "admin@9to5IT.com"
.PARAMETER EmailTo
Mandatory. The email addresses of where to send the email to. Seperate multiple emails by ",". Example: "admin@9to5IT.com, test@test.com"
.PARAMETER EmailSubject
Mandatory. The subject of the email you want to send. Example: "Cool Script - [" + (Get-Date).ToShortDateString() + "]"
.INPUTS
Parameters above
.OUTPUTS
Email sent to the list of addresses specified
.NOTES
Version: 1.0
Author: Luca Sturlese
Creation Date: 05.10.12
Purpose/Change: Initial function development
.EXAMPLE
Log-Email -LogPath "C:\Windows\Temp\Test_Script.log" -EmailFrom "admin@9to5IT.com" -EmailTo "admin@9to5IT.com, test@test.com" -EmailSubject "Cool Script - [" + (Get-Date).ToShortDateString() + "]" -SmtpServer "mydomain.com"
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][string]$LogPath,
[Parameter(Mandatory=$true)][string]$EmailFrom,
[Parameter(Mandatory=$true)][string]$EmailTo,
[Parameter(Mandatory=$true)][string]$EmailSubject,
[Parameter(Mandatory=$true)][string]$SmtpServer
)
Process{
Try{
$sBody = (Get-Content $LogPath | out-string)
#Create SMTP object and send email
$sSmtpServer = "$SmtpServer"
$oSmtp = new-object Net.Mail.SmtpClient($sSmtpServer)
$oSmtp.Send($EmailFrom, $EmailTo, $EmailSubject, $sBody)
Exit 0
}
Catch{Exit 1}
}
}
############################
#endregion Logging functions
############################
#########################
#region General functions
#########################
Function remove-logs{
Param($myscript_path)
New-Item $myscript_path\archiv -type directory -EA SilentlyContinue
Get-ChildItem $myscript_path -recurse -include *.log, *.csv, *.html, *.txt | Move-Item -destination $myscript_path\archiv
}
Function get-consolecommand{
$ext = $env:pathext -split ';' -replace '\.','*.'
$desc = @{N='Description'; e={$_.FileVersionInfo.FileDescription}}
Get-Command -Name $ext | Select-Object Name, Extension, $desc | Out-GridView
}
Function Split-Every($list, $count=4) {
$aggregateList = @()
$blocks = [Math]::Floor($list.Count / $count)
$leftOver = $list.Count % $count
for($i=0; $i -lt $blocks; $i++) {
$end = $count * ($i + 1) - 1
$aggregateList += @(,$list[$start..$end])
$start = $end + 1
}
if($leftOver -gt 0) {
$aggregateList += @(,$list[$start..($end+$leftOver)])
}
$aggregateList
}
function Get-WebRequestTable
{
param(
[Parameter(Mandatory = $true)]
$HTML,
[Parameter(Mandatory = $true)]
[int] $TableNumber
)
## Extract the tables out of the web request
$tables = @($HTML.getElementsByTagName("table"))
$table = $tables[$TableNumber]
$titles = @()
$rows = @($table.Rows)
## Go through all of the rows in the table
foreach($row in $rows)
{
$cells = @($row.Cells)
## If we've found a table header, remember its titles
if($cells[0].tagName -eq "TH")
{
$titles = @($cells | % { ("" + $_.InnerText).Trim() })
continue
}
## If we haven't found any table headers, make up names "P1", "P2", etc.
if(-not $titles)
{
$titles = @(1..($cells.Count + 2) | % { "P$_" })
}
## Now go through the cells in the the row. For each, try to find the
## title that represents that column and create a hashtable mapping those
## titles to content
$resultObject = [Ordered] @{}
for($counter = 0; $counter -lt $cells.Count; $counter++)
{
$title = $titles[$counter]
if(-not $title) { continue }
$resultObject[$title] = ("" + $cells[$counter].InnerText).Trim()
}
## And finally cast that hashtable to a PSCustomObject
[PSCustomObject] $resultObject
}
}
#Function Definitions
# Credits to - http://powershell.cz/2013/04/04/hide-and-show-console-window-from-gui/
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
function Show-Console
{
$consolePtr = [Console.Window]::GetConsoleWindow()
[Console.Window]::ShowWindow($consolePtr, 5)
}
function Hide-Console
{
$consolePtr = [Console.Window]::GetConsoleWindow()
[Console.Window]::ShowWindow($consolePtr, 0)
}
############################
#endregion General functions
############################
#####################
#region Form function
#####################
function Import-ComboBox{
<#
.SYNOPSIS
This functions helps you load items into a ComboBox.
.DESCRIPTION
Use this function to dynamically load items into the ComboBox control.
.PARAMETER ComboBox
The ComboBox control you want to add items to.
.PARAMETER Items
The object or objects you wish to load into the ComboBox's Items collection.
.PARAMETER Append
Adds the item(s) to the ComboBox without clearing the Items collection.
#>
Param (
[Parameter(Mandatory=$true)][Windows.Controls.ComboBox]$ComboBox,
[Parameter(Mandatory=$true)]$Items,
[Parameter(Mandatory=$false)][string]$DisplayMember,
[switch]$Append
)
if(-not $Append)
{
$comboBox.Items.Clear()
}
if($Items -is [Array])
{
foreach ($Item in $Items){
$comboBox.Items.Add($Item)
}
}
else
{
$comboBox.Items.Add($Items)
}
}
########################
#endregion Form function
########################
#######################
#region ip address test
#######################
function Test-IPAddressString{
<#
.SYNOPSIS
Tests to see if an IP address string is a valid address and can determine
if IP Address is responding on network.
.DESCRIPTION
Implements the .Net.IPAddress classes to validate that the string provided
can parse into an IP Address. If the parse is successful, the function returns
boolean $true unless the -FailIfInUse switch is provided.
If -FailIfInUse is specified, a $true is only returned if the IP Address
does not respond to a ping three times.
This function supports the -Verbose switch as well.
.PARAMETER IPaddressString
This is a string value representing the address that you want to test.
This value can be passed either from pipeline or as a parameter.
.PARAMETER FailIfInUse
This is a switch parameter. Specifying this in the parameter list will
cause the IP Address, if successfully parsed, to attempt to be pinged.
A successful ping result will result in a $false value being returned
if this switch is used.
.EXAMPLE
Test-IPAddressString -IPAddressString "192.168.1.1"
Using full parameter name
.EXAMPLE
Test-IPAddressString "192.168.1.1" -FailIfInUse
Using Positional parameters and specifiying to fail test if IP Address responds to ping.
.EXAMPLE
("192.168.1.1", "192.123456", "IsThisAnIP") | Test-IPAddressString -Verbose
Passing serveral potential IP Address strings to the function through the pipeline.
FailIfInUse is ommitted, so no ping attempts will be made on valid IP Addresses.
This function supports the verbose switch. Using this switch will provide you with
several indicators of progress through the process.
.NOTES
Author: Kyle Neier
Blog: http://sqldbamusings.blogspot.com
Twitter: Kyle_Neier
.LINK
http://sqldbamusings.blogspot.com/2012/04/powershell-validating-ip-address.html
#>
param(
[parameter(
Mandatory=$true,
Position=0,
ValueFromPipeline= $true
)]
[string]$IPaddressString,
[parameter(
Mandatory=$false,
Position=1,
ValueFromPipeline= $false
)]
[switch]$FailIfInUse
)
process
{
[System.Net.IPAddress]$IPAddressObject = $null
if([System.Net.IPAddress]::tryparse($IPaddressString,[ref]$IPAddressObject) -and
$IPaddressString -eq $IPAddressObject.tostring())
{
Write-Verbose "$IPaddressString successfully parsed."
if($FailIfInUse -eq $true)
{
$Pinger = new-object System.Net.NetworkInformation.Ping
$p = 1
$p_max = 3
do
{
Write-Verbose "Attempting to ping $IPaddressString - Attempt $p of $p_max"
$PingResult = $Pinger.Send("$IPaddressString")
Write-Verbose "Connection Result: $($PingResult.Status)"
$p++
Start-Sleep -Milliseconds 500
} until ($PingResult.Status -eq "Success" -or $p -gt $p_max)
if($PingResult.Status -eq "Success")
{
Write-Verbose "The IP Address $IPAddressString parsed successfully but is responding to ping."
Write-Output $false
}
else
{
Write-Verbose "The IP Address $IPAddressString parsed successfully and is not responding to ping."
Write-Output $true
}
}
else
{
Write-Verbose "The IP Address $IPAddressString parsed successfull - No ping attempt made."
Write-Output $true
}
}
else
{
Write-Verbose "The IP Address $IPAddressString could not be parsed."
Write-Output $false
}
}
}
#######################
#endregion ip address test
#######################
#######################
#region emc isilon
#######################
Function IsiPapi
{
Param(
[Parameter(Mandatory=$true)][string]$User,
[Parameter(Mandatory=$true)][string]$Password,
[Parameter(Mandatory=$true)][string]$IsilonIp,
[Parameter(Mandatory=$true)][string]$ResourceUrl,
[Parameter(Mandatory=$true)][string]$Method,
[Parameter(Mandatory=$false)][string]$JsonObject
)
# With a default cert you would normally see a cert error (code from blogs.msdn.com)
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAll : ICertificatePolicy {
public TrustAll() {}
public bool CheckValidationResult(
ServicePoint sPoint, X509Certificate cert,
WebRequest req, int problem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = new-object TrustAll
[System.Net.ServicePointManager]::SecurityProtocol = 'TLS11','TLS12','ssl3'
#[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
# create header
$EncodedAuthorization = [System.Text.Encoding]::UTF8.GetBytes($User + ':' + $Password)
$EncodedPassword = [System.Convert]::ToBase64String($EncodedAuthorization)
$Headers = @{"Authorization"="Basic $($EncodedPassword)"}
# create Uri
$BaseUrl = 'https://' + $IsilonIp +":8080"
$Uri = $BaseUrl + $ResourceUrl
switch ($Method)
{
"Get" {$IsiObject = Invoke-RestMethod -Uri $Uri -Method Get -Headers $Headers}
"Put" {$IsiObject = Invoke-RestMethod -Uri $Uri -Method Put -Headers $Headers -Body $JsonObject -ContentType "application/json; charset=utf-8"}
"Post" {$IsiObject = Invoke-RestMethod -Uri $Uri -Method Post -Headers $Headers -Body $JsonObject -ContentType "application/json; charset=utf-8"}
"Delete" {$IsiObject = Invoke-RestMethod -Uri $Uri -Method Delete -Headers $Headers -Body $JsonObject -ContentType "application/json; charset=utf-8"}
}
$IsiObject
}
#######################
#endregion emc isilon
#######################
#######################
#region superna eyelgass
#######################
Function EyeglassApi
{
Param(
[Parameter(Mandatory=$true)][string]$Apikey,
[Parameter(Mandatory=$true)][string]$EyeglassIP,
[Parameter(Mandatory=$true)][string]$ResourceUrl,
[Parameter(Mandatory=$true)][string]$Method,
[Parameter(Mandatory=$false)][string]$JsonObject
)
# With a default cert you would normally see a cert error (code from blogs.msdn.com)
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAll : ICertificatePolicy {
public TrustAll() {}
public bool CheckValidationResult(
ServicePoint sPoint, X509Certificate cert,
WebRequest req, int problem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = new-object TrustAll
[System.Net.ServicePointManager]::SecurityProtocol = 'TLS11','TLS12','ssl3'
#[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
# create header
$Headers = @{“api_key"= $apiKey}
# create Uri
$BaseUrl = 'https://' + $EyeglassIP
$Uri = $BaseUrl + $ResourceUrl
switch ($Method)
{
"Get" {$EyeglassObject = Invoke-RestMethod -Uri $Uri -Method Get -Headers $Headers -ContentType "application/json"}
"Put" {$EyeglassObject = Invoke-RestMethod -Uri $Uri -Method Put -Headers $Headers -Body $JsonObject -ContentType "application/json; charset=utf-8"}
"Post" {$EyeglassObject = Invoke-RestMethod -Uri $Uri -Method Post -Headers $Headers -Body $JsonObject -ContentType "application/json; charset=utf-8"}
"Delete" {$EyeglassObject = Invoke-RestMethod -Uri $Uri -Method Delete -Headers $Headers -Body $JsonObject -ContentType "application/json; charset=utf-8"}
}
$EyeglassObject
}
#######################
#endregion emc isilon
#######################
#######################
#region vmware
#######################
function Get-Stat2 {
<#
.SYNOPSIS Retrieve vSphere statistics
.DESCRIPTION The function is an alternative to the Get-Stat cmdlet.
It's primary use is to provide functionality that is missing
from the Get-Stat cmdlet.
.NOTES Author: Luc Dekens
.PARAMETER Entity
Specify the VIObject for which you want to retrieve statistics
This needs to be an SDK object
.PARAMETER Start
Start of the interval for which to retrive statistics
.PARAMETER Finish
End of the interval for which to retrive statistics
.PARAMETER Stat
The identifiers of the metrics to retrieve
.PARAMETER Instance
The instance property of the statistics to retrieve
.PARAMETER Interval
Specify for which interval you want to retrieve statistics.
Allowed values are RT, HI1, HI2, HI3 and HI4
.PARAMETER MaxSamples
The maximum number of samples for each metric
.PARAMETER QueryMetrics
Switch to indicate that the function should return the available
metrics for the Entity specified
.PARAMETER QueryInstances
Switch to indicate that the function should return the valid instances
for a specific Entity and Stat
.EXAMPLE
PS> Get-Stat2 -Entity $vm.Extensiondata -Stat "cpu.usage.average" -Interval "RT"
#>
[CmdletBinding()]
param (
[parameter(Mandatory = $true, ValueFromPipeline = $true)]
[PSObject]$Entity,
[DateTime]$Start,
[DateTime]$Finish,
[String[]]$Stat,
[String]$Instance = "",
[ValidateSet("RT","HI1","HI2","HI3","HI4")]
[String]$Interval = "RT",
[int]$MaxSamples,
[switch]$QueryMetrics,
[switch]$QueryInstances)
# Test if entity is valid
$EntityType = $Entity.GetType().Name
if(!(("HostSystem",
"VirtualMachine",
"ClusterComputeResource",
"Datastore",
"ResourcePool") -contains $EntityType)) {
Throw "-Entity parameters should be of type HostSystem, VirtualMachine, ClusterComputeResource, Datastore or ResourcePool"
}
$perfMgr = Get-View (Get-View ServiceInstance).content.perfManager
# Create performance counter hashtable
$pcTable = New-Object Hashtable
$keyTable = New-Object Hashtable
foreach($pC in $perfMgr.PerfCounter){
if($pC.Level -ne 99){
if(!$pctable.containskey($pC.GroupInfo.Key + "." + $pC.NameInfo.Key + "." + $pC.RollupType)){
$pctable.Add(($pC.GroupInfo.Key + "." + $pC.NameInfo.Key + "." + $pC.RollupType),$pC.Key)
$keyTable.Add($pC.Key, $pC)
}
}
}
# Test for a valid $Interval
if($Interval.ToString().Split(" ").count -gt 1){
Throw "Only 1 interval allowed."
}
$intervalTab = @{"RT"=$null;"HI1"=0;"HI2"=1;"HI3"=2;"HI4"=3}
$dsValidIntervals = "HI2","HI3","HI4"
$intervalIndex = $intervalTab[$Interval]
if($EntityType -ne "datastore"){
if($Interval -eq "RT"){
$numinterval = 20
}
else{
$numinterval = $perfMgr.HistoricalInterval[$intervalIndex].SamplingPeriod
}
}
else{
if($dsValidIntervals -contains $Interval){
$numinterval = $null
if(!$Start){
$Start = (Get-Date).AddSeconds($perfMgr.HistoricalInterval[$intervalIndex].SamplingPeriod - $perfMgr.HistoricalInterval[$intervalIndex].Length)
}
if(!$Finish){
$Finish = Get-Date
}
}
else{
Throw "-Interval parameter $Interval is invalid for datastore metrics."
}
}
# Test if QueryMetrics is given
if($QueryMetrics){
$metrics = $perfMgr.QueryAvailablePerfMetric($Entity.MoRef,$null,$null,$numinterval)
$metricslist = @()
foreach($pmId in $metrics){
$pC = $keyTable[$pmId.CounterId]
$metricslist += New-Object PSObject -Property @{
Group = $pC.GroupInfo.Key
Name = $pC.NameInfo.Key
Rollup = $pC.RollupType
Id = $pC.Key
Level = $pC.Level
Type = $pC.StatsType
Unit = $pC.UnitInfo.Key
}
}
return ($metricslist | Sort-Object -unique -property Group,Name,Rollup)
}
# Test if start is valid
if($Start -ne $null -and $Start -ne ""){
if($Start.gettype().name -ne "DateTime") {
Throw "-Start parameter should be a DateTime value"