forked from texhex/BiosSledgehammer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MPSXM.psm1
2296 lines (1812 loc) · 59 KB
/
MPSXM.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
# Michael's PowerShell eXtension Module
# Version 3.21.1
# https://github.com/texhex/MPSXM
#
# Copyright © 2010-2017 Michael 'Tex' Hex
# Licensed under the Apache License, Version 2.0.
#
# Import this module like this in case it is locatd in the same folder as your script
# Import-Module "$PSScriptRoot\MPSXM.psm1"
#
# In case you edit this file, new functions will not be found by the current PS session. Use -Force in this case.
# Import-Module "$PSScriptRoot\MPSXM.psm1" -Force
#
#
# Common header for your script:
<#
#(Script description)
#(Your name)
#(Version of script)
#This script requires PowerShell 4.0 or higher
#requires -version 4.0
#Guard against common code errors
Set-StrictMode -version 2.0
#Terminate script on errors
$ErrorActionPreference = 'Stop'
#Import
Import-Module "$PSScriptRoot\MPSXM.psm1" -Force
#>
# Before adding a new function, please see
# [Approved Verbs for Windows PowerShell Commands] http://msdn.microsoft.com/en-us/library/ms714428%28v=vs.85%29.aspx
#
# To run a PowerShell script from the command line, use
# powershell.exe [-NonInteractive] -ExecutionPolicy Bypass -File "C:\Script\DoIt.ps1"
#requires -version 4.0
#Guard against common code errors
#We do not use "Latest" because the rules are not documented
Set-StrictMode -version 2.0
#Terminate script on errors
$ErrorActionPreference = 'Stop'
#Next major version notes:
# Get-StringIsNullOrWhiteSpace() should be deleted (replaced with Test-String)
# Get-StringHasData() should be deleted (replaced with Test-String)
# Get-RunningInISE() should be deleted (replaced with Test-InISE)
# Add-RegistryValue() should be be deleted (replaced with Set-RegistryValue)
function Get-CurrentProcessBitness()
{
<#
.SYNOPSIS
Returns information about the current powershell process.
.PARAMETER Is64bit
Returns $True if the current script is running as 64-bit process.
.PARAMETER Is32bit
Returns $True if the current script is running as 32-bit process.
.PARAMETER IsWoW
Returns $True if the current script is running as 32-bit process on a 64-bit machine (Windows on Windows).
.OUTPUTS
Boolean, depending on parameter
#>
[OutputType([bool])]
param (
[Parameter(ParameterSetName="32bit",Mandatory=$True)]
[switch]$Is32bit,
[Parameter(ParameterSetName="WoW",Mandatory=$True)]
[switch]$IsWoW,
[Parameter(ParameterSetName="64bit",Mandatory=$True)]
[switch]$Is64bit
)
switch ($PsCmdlet.ParameterSetName)
{
"64bit"
{
$result=$false
if ( [System.Environment]::Is64BitOperatingSystem)
{
if ( [System.Environment]::Is64BitProcess )
{
$result=$true
}
}
return $result
}
"32bit"
{
return !([System.Environment]::Is64BitProcess)
}
"WoW"
{
#WoW is only support on 64-bit
$result=$false
if ( [System.Environment]::Is64BitOperatingSystem)
{
if ( Get-CurrentProcessBitness -Is32bit )
{
#32-bit Process on a 64-bit machine -> WOW on
$result=$true
}
}
return $result
}
} #switch
}
function Get-OperatingSystemBitness()
{
<#
.SYNOPSIS
Returns information about the current operating system
.PARAMETER Is64bit
Returns $True if the current operating system is 64-bit
.PARAMETER Is32bit
Returns $True if the current operating system is 32-bit
.OUTPUTS
Boolean, depending on parameter
#>
[OutputType([bool])]
param (
[Parameter(ParameterSetName="32bit",Mandatory=$True)]
[switch]$Is32bit,
[Parameter(ParameterSetName="64bit",Mandatory=$True)]
[switch]$Is64bit
)
switch ($PsCmdlet.ParameterSetName)
{
"64bit"
{
$result=$false
if ( [System.Environment]::Is64BitOperatingSystem)
{
$result=$true
}
return $result
}
"32bit"
{
return !([System.Environment]::Is64BitOperatingSystem)
}
} #switch
}
function Get-StringIsNullOrWhiteSpace()
{
<#
.SYNOPSIS
Returns true if the string is either $null, empty, or consists only of white-space characters (uses [Test-String -IsNullOrWhiteSpace] internally)
.PARAMETER String
The string value to be checked
.OUTPUTS
$true if the string is either $null, empty, or consists only of white-space characters, $false otherwise
#>
[OutputType([bool])]
param (
[Parameter(Mandatory=$True,Position=1)]
[AllowEmptyString()] #we need this or PowerShell will complain "Cannot bind argument to parameter 'string' because it is an empty string."
[string]$string
)
return Test-String -IsNullOrWhiteSpace $string
}
function Get-StringHasData()
{
<#
.SYNOPSIS
Returns true if the string contains data (does not contain $null, empty or only white spaces). Uses [Test-String -HasData] internally.
.PARAMETER string
The string value to be checked
.OUTPUTS
$true if the string is not $null, empty, or consists only of white space characters, $false otherwise
#>
[OutputType([bool])]
param (
[Parameter(Mandatory=$True,Position=1)]
[AllowEmptyString()] #we need this or PowerShell will complain "Cannot bind argument to parameter 'string' because it is an empty string."
[string]$string
)
return Test-String -HasData $string
}
<#
-IsNullOrWhiteSpace:
Helper function for [string]::IsNullOrWhiteSpace - http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace%28v=vs.110%29.aspx
Test-String "a" -IsNullorWhitespace #false
Test-String $null -IsNullorWhitespace #$true
Test-String "" -IsNullorWhitespace #$true
Test-String " " -IsNullorWhitespace #$true
Test-String " " -IsNullorWhitespace #$true
-HasData
String is not IsNullOrWhiteSpace
-Contains
Standard Contains() or IndexOf
-StartsWith
Uses string.StartsWith() with different parameters
#>
function Test-String()
{
<#
.SYNOPSIS
Tests the given string for a condition
.PARAMETER String
The string the specified operation should be performed on
.PARAMETER IsNullOrWhiteSpace
Returns true if the string is either $null, empty, or consists only of white-space characters.
.PARAMETER HasData
Returns true if the string contains data (not $null, empty or only white spaces)
.PARAMETER Contains
Returns true if string contains the text in SearchFor. A case-insensitive (ABCD = abcd) is performed by default.
.PARAMETER StartsWith
Returns true if the string starts with the text in SearchFor. A case-insensitive (ABCD = abcd) is performed by default.
.PARAMETER SearchFor
The string beeing sought
.PARAMETER CaseSensitive
Perform an operation that respect letter casing, so [ABC] is different from [aBC].
.OUTPUTS
bool
#>
[OutputType([bool])]
param (
[Parameter(Mandatory=$false,Position=1)] #false or we can not pass empty strings
[string]$String=$null,
[Parameter(ParameterSetName="HasData", Mandatory=$true)]
[switch]$HasData,
[Parameter(ParameterSetName="IsNullOrWhiteSpace", Mandatory=$true)]
[switch]$IsNullOrWhiteSpace,
[Parameter(ParameterSetName="Contains", Mandatory=$true)]
[switch]$Contains,
[Parameter(ParameterSetName="StartsWith", Mandatory=$true)]
[switch]$StartsWith,
[Parameter(ParameterSetName="Contains", Position=2, Mandatory=$false)] #$False or we can not pass an empty string in
[Parameter(ParameterSetName="StartsWith", Position=2, Mandatory=$false)]
[string]$SearchFor,
[Parameter(ParameterSetName="Contains", Mandatory=$false)]
[Parameter(ParameterSetName="StartsWith",Mandatory=$false)] #$False or we can not pass an empty string in
[Switch]$CaseSensitive=$false
)
$result=$null
switch ($PsCmdlet.ParameterSetName)
{
"IsNullOrWhiteSpace"
{
if ([string]::IsNullOrWhiteSpace($String))
{
$result=$true
}
else
{
$result=$false
}
}
"HasData"
{
$result= -not (Test-String -IsNullOrWhiteSpace $String)
}
"Contains"
{
if ( $CaseSensitive )
{
$result=$String.Contains($SearchFor)
}
else
{
#from this answer on StackOverFlow: http://stackoverflow.com/a/444818/612954
# by JaredPar - http://stackoverflow.com/users/23283/jaredpar
#and just for reference: These lines do NOT work.
#Only this blog post finally told me what the correct syntax is: http://threemillion.net/blog/?p=331
#$index=$String.IndexOf($SearchFor, ([System.StringComparer]::OrdinalIgnoreCase))
#$index=$String.IndexOf($SearchFor, "System.StringComparison.OrdinalIgnoreCase")
#We could also use [StringComparison]::CurrentCultureIgnoreCase but it seems OrdinalIgnoreCase is better (Faster)
$result=( $String.IndexOf($SearchFor,[StringComparison]::OrdinalIgnoreCase) ) -ge 0
}
}
"StartsWith"
{
if ( $CaseSensitive )
{
$result=$String.StartsWith($SearchFor)
}
else
{
$result=$String.StartsWith($SearchFor,[StringComparison]::OrdinalIgnoreCase)
}
}
}
return $result
}
#Yes, I'm aware of $env:TEMP but this will always return a 8+3 path, e.g. C:\USERS\ADMIN~1\AppData..."
#This function returns the real path without that "~" garbage
function Get-TempFolder()
{
<#
.SYNOPSIS
Returns a path to the temporary folder without any (8+3) paths in it
.OUTPUTS
Path to temporary folder without an ending "\"
#>
$temp=[System.IO.Path]::GetTempPath()
if ( $temp.EndsWith("\") )
{
$temp=$temp.TrimEnd("\")
}
return $temp
}
Function Get-ModuleAvailable {
<#
.SYNOPSIS
Returns true if the module exist; it uses a a method that is about 10 times faster then using Get-Module -ListAvailable
.PARAMETER name
The name of the module to be checked
.OUTPUTS
$true if the module is available, $false if not
#>
[OutputType([bool])]
param(
[Parameter(Mandatory=$True,Position=1)]
[ValidateNotNullOrEmpty()]
[string]$Name
)
#First check if the requested module is already available in this session
if(-Not (Get-Module -name $name))
{
#The correct way would be to now use [Get-Module -ListAvailable] like this:
#Creating the list of available modules takes some seconds; Therfore use a cache on module level:
#if ($script:Test_MPXModuleAvailable_Cache -eq $null) {
# $script:Test_MPXModuleAvailable_Cache=Get-Module -ListAvailable | ForEach-Object {$_.Name}
#}
#if ($Test_MPXModuleAvailable_Cache -contains $name)
#{
# #module is available and will be loaded by PowerShell when requested
# return $true
#} else {
# #this module is not available
# return $false
#}
#However, this function is a performance killer as it reads every cmdlet, dll, and whatever
#from any module that is available.
#
#Therefore we will simply try to import the module using import-module on local level
#and then return if this has worked. This way, only the module requested is fully loaded.
#Since we only load it to the local level, we make sure not to change the calling level
#if the caller does not want that module to be loaded.
#
#Given that the script (that has called us) will the use a cmdlet from the module,
#the module is already loaded in the runspace and the next call to this function will be
#a lot faster since get-module will then return $TRUE.
$mod=Import-Module $name -PassThru -ErrorAction SilentlyContinue -Scope Local
if ($mod -ne $null)
{
return $true
}
else
{
return $false
}
} else {
#module is already available in this runspace
return $true
}
}
Function Get-ComputerLastBootupTime(){<#
.SYNOPSIS
Returns the date and time of the last bootup time of this computer.
.OUTPUTS
DateTime (Kind = Local) that is the last bootup time of this computer
#> [OutputType([datetime])] #param(#) $obj = Get-CIMInstance Win32_OperatingSystem -Property "LastBootupTime" return $obj.LastBootUpTime}Function Get-RunningInISE()
{
<#
.SYNOPSIS
Returns if the current script is executed by Windows PowerShell ISE (uses Test-IsISE internally)
.OUTPUTS
$TRUE if running in ISE, FALSE otherise
#> [OutputType([bool])]
param()
return Test-IsISE
}
#From: http://stackoverflow.com/a/25224840# by kuujinbo (http://stackoverflow.com/users/604196/kuujinbo)Function Test-IsISE()
{
<#
.SYNOPSIS
Returns if the current script is executed by Windows PowerShell ISE
.OUTPUTS
$TRUE if running in ISE, FALSE otherise
#> [OutputType([bool])]
param()
try
{
return $psISE -ne $null
}
catch
{
return $false
}
}
function Start-TranscriptTaskSequence()
{
<#
.SYNOPSIS
If the scripts runs in MDT or SCCM, the transcript will be stored in the path LOGPATH defines. If not, C:\WINDOWS\TEMP is used.
.PARAMETER NewLog
When set, will create a log file every time a transcript is started
.OUTPUTS
None
#> param(
[Parameter(Mandatory=$False)]
[switch]$NewLog=$False
) try
{
$tsenv = New-Object -COMObject Microsoft.SMS.TSEnvironment
$logPath = $tsenv.Value("LogPath")
Write-Verbose "Start-TranscriptTaskSequence: Running in task sequence, using folder [$logPath]"
}
catch
{
$logPath = $env:windir + "\temp"
Write-Verbose "Start-TranscriptTaskSequence: This script is not running in a task sequence, will use [$logPath]"
}
$logName=Split-Path -Path $myInvocation.ScriptName -Leaf
if ( $NewLog )
{
Start-TranscriptIfSupported -Path $logPath -Name $logName -NewLog } else { Start-TranscriptIfSupported -Path $logPath -Name $logName }}function Start-TranscriptIfSupported {
<#
.SYNOPSIS
Starts a transscript, but ignores if the host does not support it.
.PARAMETER Path
The path where to store the transcript. If empty, the %TEMP% folder is used.
.PARAMETER Name
The name of the log file. If empty, the file name of the calling script is used.
.PARAMETER NewLog
Create a new log file every time a transcript is started ([Name].log-XX.txt)
.OUTPUTS
None
#> param(
[Parameter(Mandatory=$False,Position=1)]
[string]$Path=$env:TEMP,
[Parameter(Mandatory=$False,Position=2)]
[string]$Name,
[Parameter(Mandatory=$False)]
[switch]$NewLog=$False
)
if ( Test-String -IsNullOrWhiteSpace $Name )
{
$Name=Split-Path -Path $myInvocation.ScriptName -Leaf
}
$logFileTemplate = "$($Name).log"
$extension="txt" #always use lower case chars only!
#only needed if we need to add something
$fileNameTail=""
if ( $NewLog )
{
#we need to create log file like <SCRIPTNAME.ps>-Log #001.txt
$filter="$($logFileTemplate)-??.$extension"
[uint32]$value=1
$existing_files=Get-ChildItem -Path $Path -File -Filter $filter -Force
#In case we get $null this means that no files were found. Nothing more to
if ( $existing_files -ne $null )
{
#at least one other file exists. Reorder so the log file with the highest name is at the end
$existing_files=$existing_files | Sort-Object -Property "Name"
#check if the result is one file or not
if ( $existing_files -is [array] )
{
$temp=$existing_files[$existing_files.Count-1].Name
}
else
{
$temp=$existing_files.Name
}
#now access the last object in the list
$temp=$temp.ToLower()
#cut the ".txt" part from the end
$temp=$temp.TrimEnd(".$extension")
#Extract the the last two digitis, e.g. "13"
$curValueText=$temp.Substring($temp.Length-2, 2)
#convert to int so we can calculate with it. Maybe this will fail in which case we default to 99
try
{
[uint32]$value=$curValueText
#add one to the value
$value++
}
catch
{
$value=99
}
#Final check. If the value is > 99, use 99 anyway
if ( $value -gt 99 )
{
$value=99
}
#Done calculating $value
}
#Ensure that we have leading zeros if required
$fileNameTail="-{0:D2}" -f $value
}
$logFile = "$Path\$($logFileTemplate)$($filenameTail).$extension"
try
{
write-verbose "Trying to execute Start-Transcript for $logFile"
Start-Transcript -Path $logfile
}
catch [System.Management.Automation.PSNotSupportedException] {
# The current PowerShell Host doesn't support transcribing
write-host "Start-TranscriptIfSupported: The current PowerShell host doesn't support transcribing; no log will be generated to [$logfile]"
}}function Stop-TranscriptIfSupported {
<#
.SYNOPSIS
Stops a transscript, but ignores if the host does not support it.
.OUTPUTS
None
#> try
{
Stop-Transcript
}
catch [System.Management.Automation.PSNotSupportedException]
{
write-host "Stop-TranscriptIfSupported WARNING: The current PowerShell host doesn't support transcribing. No log was generated."
}}function Show-MessageBox {
<#
.SYNOPSIS
Shows the message box to the user using a message box.
.PARAMETER Message
The message to be displayed inside the message box.
.PARAMETER Titel
The title for the message box. If empty, the full script filename is used.
.PARAMETER Critical
Show an critical icon inside the message box. If not set, an information icon is used.
.PARAMETER Huge
Adds extra lines to the message to ensure the message box appears bigger.
.OUTPUTS
None
#>
param(
[Parameter(Mandatory=$True,Position=1)]
[ValidateNotNullOrEmpty()]
[string]$Message,
[Parameter(Mandatory=$False,Position=2)]
[string]$Titel,
[Parameter(Mandatory=$False)]
[switch]$Critical,
[Parameter(Mandatory=$False)]
[switch]$Huge
)
#make sure the assembly is loaded
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$type=[System.Windows.Forms.MessageBoxIcon]::Information
if ( $Critical )
{
$type=[System.Windows.Forms.MessageBoxIcon]::Error
}
if ( Test-String -IsNullOrWhiteSpace $Titel )
{
$Titel=$myInvocation.ScriptName
}
if ( $Huge )
{
$crlf="`r`n"
$crlf5="$crlf$crlf$crlf$crlf$crlf"
$Message="$Message $crlf5$crlf5$crlf5$crlf5$crlf5$crlf5"
}
#display message box
$ignored=[System.Windows.Forms.MessageBox]::Show($message, $Titel, 0, $type)
}
#From http://stackingcode.com/blog/2011/10/27/quick-random-string
# by Adam Boddington
function Get-RandomString {
<#
.SYNOPSIS
Returns a random string (only Aa-Zz and 0-9 are used).
.PARAMETER Length
The length of the string that should be generated.
.OUTPUTS
Generated random string.
#>
param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
[ValidateNotNullOrEmpty()]
[int]$Length
)
$set = "abcdefghijklmnopqrstuvwxyz0123456789".ToCharArray()
$result = ""
for ($x = 0; $x -lt $Length; $x++)
{
$result += $set | Get-Random
}
return $result
}
<#
This is most basic way I could think of to represent a hash table with single string values as a file
; Comment (INI style)
# also understood as comment (PowerShell style)
;Still a comment
;Also this.
Key1==Value1
Key2==Value2
...
#>
function Read-StringHashtable() {
<#
.SYNOPSIS
Reads a hashtable from a file where the Key-Value pairs are stored as Key==Value
.PARAMETER File
The file to read the hashtable from
.OUTPUTS
Hashtable
#>
[OutputType([Hashtable])]
param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
[string]$File
)
$result=@{}
write-verbose "Reading hashtable from $file"
if ( Test-Path $file )
{
$data=Get-Content $file -Raw
$lines=$data -split "`n" #we split at LF, not CR+LF in case someone has used the wrong line ending AGAIN
if ( ($lines -eq $null) -or ($lines.Count -eq 0) )
{
#OK, this didn't worked. Maybe someone used pure CR?
$lines=$data -split "`r"
}
foreach ($line in $lines)
{
#just to make sure that nothing was left over
$line=$line -replace "´r",""
$line=$line -replace "´n",""
$line=$line.Trim()
if ( !($line.StartsWith("#")) -and !($line.StartsWith(";")) -and !(Test-String -IsNullOrWhiteSpace $line) )
{
#this has to be a setting
$setting=$line -split "=="
if ( $setting.Count -ne 2 ) {
throw New-Exception -InvalidFormat -Explanation "Error parsing [$line] as key-value pair - did you forgot to use '=='?"
}
else
{
$name=$setting[0].Trim()
$value=$setting[1].Trim()
#I'm unsure if this information is of any use
#write-verbose "Key-Value pair found: [$name] : [$value]"
if ( $result.ContainsKey($name) )
{
throw New-Exception -InvalidOperation "Can not add key [$name] (Value: $value) because a key of this name already exists"
}
else
{
$result.Add($name, $value)
}
}
}
}
}
else
{
throw New-Exception -FileNotFound "The file [$file] does not exist or is not accessible"
}
return $result
}
#The verb "Humanize" is taken from this great project: [Humanizer](https://github.com/MehdiK/Humanizer)
#Idea from [Which Disk is that volume on](http://www.uvm.edu/~gcd/2013/01/which-disk-is-that-volume-on/) by Geoff Duke
function ConvertTo-HumanizedBytesString {
<#
.SYNOPSIS
Returns a string optimized for readability.
.PARAMETER bytes
The value of bytes that should be returned as humanized string.
.OUTPUTS
A humanized string that is rounded (no decimal points) and optimized for readability. 1024 becomes 1kb, 179111387136 will be 167 GB etc.
#>
[OutputType([String])]
param (
[Parameter(Mandatory=$True,Position=1)]
[AllowEmptyString()]
[int64]$bytes
)
#Better set strict mode on function scope than on module level
Set-StrictMode -version 2.0
#Original code was :N2 which means "two decimal points"
if ( $bytes -gt 1pb ) { return "{0:N0} PB" -f ($bytes / 1pb) }
elseif ( $bytes -gt 1tb ) { return "{0:N0} TB" -f ($bytes / 1tb) }
elseif ( $bytes -gt 1gb ) { return "{0:N0} GB" -f ($bytes / 1gb) }
elseif ( $bytes -gt 1mb ) { return "{0:N0} MB" -f ($bytes / 1mb) }
elseif ( $bytes -gt 1kb ) { return "{0:N0} KB" -f ($bytes / 1kb) }
else { return "{0:N0} Bytes" -f $bytes }
}
function ConvertTo-Version()
{
<#
.SYNOPSIS
Returns a VERSION object with the version number converted from the given text.
.PARAMETER text
The input string to be converted, e.g. 1.3.44.
.PARAMETER RespectLeadingZeros
Respect leading zeros by shifting the parts right, e.g. 1.02.3 becomes 1.0.2.3.
.OUTPUTS
A version object or $NULL if the text could not be parsed
#>
[OutputType([System.Version])]
param(
[Parameter(Mandatory=$False,ValueFromPipeline=$True)]
[string]$Text="",
[Parameter(Mandatory=$False,ValueFromPipeline=$True)]
[switch]$RespectLeadingZeros=$false
)
try
{
[version]$version=$Text
}
catch
{
$version=$null
}
if ( $version -ne $null)
{
#when we are here, the version could be parsed
if ( $RespectLeadingZeros) {
#Reminder: Version object defines Major.Minor.Build.Revision
#In case the version only contains of a major version, there is nothing to respect.
#Whoever wants to have leading zeros for a major version respected should be killed.
if ( $version.Minor -gt -1 )
{
$verarray=@()
$tokens=$Text.Split(".")
#always add the major version as is
$verArray += [int]$tokens[0]
if ( $tokens.Count -ge 2)
{
$minor=$tokens[1]
if ( $minor.StartsWith(0) )
{
#Add 0 as minor and the minor version as Build
$verArray += 0
}
$verArray += [int]$minor
if ( $tokens.Count -ge 3)
{
$build=$tokens[2]
if ( $build.StartsWith(0) )
{
$verArray += 0
}
$verArray += [int]$build
if ( $tokens.Count -ge 4)
{
$revision=$tokens[3]
if ( $revision.StartsWith(0) )
{
$verArray += 0
}
$verArray += [int]$revision
}
}
}
#Turn the array to a string
$verString=""
foreach ($part in $verarray)
{
$verString += "$part."
}
$verString=$verString.TrimEnd(".")
#Given that version can only hold Major.Minor.Build.Revision, we need to check if we have four or less entries
if ( $verArray.Count -ge 5 )
{
throw New-Exception -InvalidArgument "Parsing given text resulted in a version that is incompatible with System.Version ($verString)"
}
else
{
$versionNew=New-Object System.Version $verarray
$version=$versionNew
}
#all done
}
}
}
return $version
}
function Exit-Context {
<#
.SYNOPSIS
Will exit from the current context and sets an exit code. Nothing will be done when running in ISE.
.PARAMETER ExitCode
The number the exit code should be set to.
.PARAMETER Force
Will enfore full exit by using ENVIRONMENT.Exit()
.OUTPUTS
None
#>
param(
[Parameter(Mandatory=$True,Position=1)]
[ValidateNotNullOrEmpty()]
[int32]$ExitCode,
[Parameter(Mandatory=$False)]
[switch]$Force=$False
)
write-verbose "Exit-Context: Will exit with exit code $ExitCode"
if ( Get-RunningInISE )