roeprofile.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
function Build-PowerShellModule {

    <#
        .SYNOPSIS
        Builds PowerShell module from functions found in given path

        .DESCRIPTION
        Takes function from seperate files in FunctionsPath and builds a PowerShell module to ModuleDir.
        Existing module files in ModuleDir will be overwritten.

        FunctionsPath must include one separate file for each function to include.
        The full content of the file will be included as a function. If a Function declaration is not found as the first line, it will be automatically created.

        Build version for module is incrementeted by 1 on each build, relative to version found in ManifestFile.
        

        .PARAMETER FunctionsPath
        Path to individual functions files

        .PARAMETER ModuleDir
        Directory to export finished module to

        .PARAMETER ModuleName
        Name of module. If omitted name will be taken from Manifest. If no manifest can be found, name will be autogenerated as Module-yyyyMMdd

        .PARAMETER ManifestFile
        Path to .psd1 file to use as template. If omitted the first .psd1 file found in ModuleDir will be used. If no file can be found a default will be created

        .PARAMETER Description
        Description of module

        .PARAMETER RunScriptAtImport
        Script to run when module is imported. Will be added to .psm1 as-is

    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateScript({Test-Path -path $_})]
        [String]$FunctionsPath,
        [Parameter(Mandatory = $true)]
        [string]$ModuleDir,
        [Parameter(Mandatory = $false)]
        [string]$ModuleName,
        [Parameter(Mandatory = $false)]
        [String]$ManifestFile,
        [Parameter(Mandatory = $false)]
        [String]$Description,
        [Parameter(Mandatory = $false)]
        [String]$RunScriptAtImport
    )

    $ErrorActionPreference = 'Stop'

    switch ($ModuleDir) {
        {-not (Test-Path -Path $_ -ErrorAction SilentlyContinue)} {Write-Verbose "Creating $_" ; $null = New-Item -Path $_ -ItemType Directory ; break}
        {-not (Get-Item -Path $ModuleDir -ErrorAction SilentlyContinue).PSIsContainer} {Throw "$ModuleDir is not a valid directory path"}
        default {}
    }

    # Make sure we have a valid Manifest file
    if ([string]::isnullorwhitespace($ManifestFile)) {
        Write-Verbose "Getting first manifest file from $ModuleDir"
        $ManifestFile = (Get-Item -Path (Join-Path -Path $ModuleDir -ChildPath "*.psd1") | Select-Object -First 1).FullName
    }

    if ([string]::isnullorwhitespace($ManifestFile)) {
        if ([string]::IsNullOrWhiteSpace($ModuleName)) {
            Write-Verbose "Generating Modulename"
            $ModuleName = "Module-$(Get-Date -format yyyyMMdd)"
        }
        Write-Verbose "Creating default manifestfile"
        $ManifestFile = Join-Path -Path $ModuleDir -ChildPath "$ModuleName.psd1"
        New-ModuleManifest -Path $ManifestFile -ModuleVersion 0.0.0
    }
    
    # Get content of manifest
    $ManifestHash = [ScriptBlock]::Create((Get-Content -Path $ManifestFile -Raw)).InvokeReturnAsIs()

    # Make sure destination files will end up in the ModuleDir
    if ([string]::isnullorwhitespace($ModuleName)) {
        Write-Verbose "Naming module after $Manifestfile"
        $ModuleName = split-path -path $ManifestFile -LeafBase    
    }

    $ManifestFile   = Join-Path -path $moduleDir -childPath "$ModuleName.psd1" 
    $moduleFile     = Join-Path -Path $ModuleDir -ChildPath "$ModuleName.psm1"

    $ManifestHash["RootModule"] = "$ModuleName.psm1"
    if (-not [String]::isnullorwhitespace($Description)) {
        Write-Verbose "Adding description to manifest"
        $ManifestHash["Description"] = $Description
    }

    # Increment version number
    [Version]$Version = $manifestHash["ModuleVersion"]
    if ($Version.Minor -eq 9 -and $Version.Build -eq 9) {
        Write-Verbose "Incrementing major version"
        [version]$Version = "$($version.Major + 1).0.0"
    }
    elseif ($Version.Build -lt 9) {
        Write-Verbose "Incrementing build version"
        [version]$Version = "$($Version.Major).$($Version.Minor).$($Version.Build + 1)"
    }
    elseif ($Version.Minor -lt 9 -and $version.build -eq 9){
        Write-Verbose "Incrementing minor version"
        [Version]$Version = "$($Version.Major).$($Version.Minor + 1).0"
    }
    else {
        Write-Warning "WTF?"
    }
 
    # Get content of PS1 files in FunctionsPath
    $moduleContent = @(
        Get-Item -ErrorAction SilentlyContinue -Path (Join-Path -Path $FunctionsPath -childPath "*.ps1") | ForEach-Object -Process {
            Write-Verbose "Processing functionfile: $_"
            $FunctionsToExport += @($_.BaseName)
            $FunctionContent = Get-Content -Path $_ | Where-Object {-not [String]::isnullorwhitespace($_)}
            if ($FunctionContent[0].trim() -match "^Function") {
                Write-Verbose "Detected function"
                Get-Content -Path $_ -Raw
            }
            else {
                Write-Verbose "Adding function declaration"
                $Return = @()
                $Return += "Function $($_.BaseName) {"
                $Return += Get-Content -Path $_ -Raw
                $Return += "}"
                $Return
            }
        }
    )

    if (-not [String]::IsNullOrWhiteSpace($RunScriptAtImport)) {
        Write-Verbose "Adding RunScriptAtImport"
        $moduleContent += $RunScriptAtImport
    }
    
    Write-Verbose "Writing $Modulefile"
    Set-Content -Path $moduleFile -Value $moduleContent


    # Update manifest

    $manifestSplat = @{
        Path                 = $manifestFile
        ModuleVersion        = $version
    }
    $manifestSplat['FunctionsToExport']    = $functionsToExport 
    Write-Verbose "Updating manifest"
    Update-ModuleManifest @manifestSplat

    $props = [ordered]@{"ModuleName" = $ModuleName
                        "Version" = $Version
                        "Manifest" = (Get-Item -Path $manifestFile).FullName
                        "Module" = (Get-Item -Path $moduleFile).FullName
                        }
    return New-Object -TypeName PSObject -Property $props 

}

Function Clear-UserVariables {
    #Clear any variable not defined in the $SysVars variable
    if (Get-Variable -Name SysVars -ErrorAction SilentlyContinue) {
        $UserVars = get-childitem variable: | Where-Object {$SysVars -notcontains $_.Name} 
        ForEach ($var in $UserVars) {
            Write-Host ("Clearing $" + $var.name)
            Remove-Variable $var.name -Scope 'Global'
        }    
    }
    else {
        Write-Warning "SysVars variable not set"
        break
    }
}
Function Connect-EXOPartner {
    param(
        [parameter(Mandatory = $false)]
        [System.Management.Automation.CredentialAttribute()] 
        $Credential, 
        [parameter(Mandatory = $false)]
        [string] 
        $TenantDomain 
    )
    if (-not $TenantDomain) {
        $TenantDomain = Read-Host -Prompt "Input tenant domain, e.g. hosters.com"
    }
    if (-not $Credential) {
        $Credential = Get-Credential -Message "Credentials for CSP delegated admin, e.g. ""bm@klestrup.dk""/""password"""
    }
    $ExSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell-liveid?DelegatedOrg=$TenantDomain" -Credential $Credential -Authentication Basic -AllowRedirection
    if ($ExSession) {Import-PSSession $ExSession}
}

Function ConvertTo-HashTable {
    <#
        .SYNOPSIS
        Converts PS Object, or JSON string, to Hashtable
    #>

    # https://stackoverflow.com/questions/3740128/pscustomobject-to-hashtable
    param (
        [Parameter(ValueFromPipeline)]
        $PSObject
    )
  
    process {
        if ($null -eq $PSObject -and $null -eq $JSON ) { 
            return $null 
        }
          
        if ($PSObject -is [string]) {
            $PSObject = $PSObject | ConvertFrom-Json
        }
  
        if ($PSObject -is [System.Collections.IEnumerable] -and $PSObject -isnot [string]) {
            $collection = @(
                foreach ($object in $PSObject) { ConvertTo-HashTable $object }
            )
            Write-Output -NoEnumerate $collection
        }
        elseif ($PSObject -is [psobject]) {
            $hash = [ordered]@{}
            foreach ($property in $PSObject.PSObject.Properties) {
                $hash[$property.Name] = ConvertTo-HashTable $property.Value
            }
            return $hash
        }
        else {
            return $PSObject
        }
    }
} 


Function Get-COMObjects {
    if (-not $IsLinux) {
        $Objects = Get-ChildItem HKLM:\Software\Classes -ErrorAction SilentlyContinue | Where-Object {$_.PSChildName -match '^\w+\.\w+$' -and (Test-Path -Path "$($_.PSPath)\CLSID")}
        $Objects | Select-Object -ExpandProperty PSChildName
    }
}

Function Get-MatchingString {
    param(
        [string]$Text,
        [string]$RegEx,
        [switch]$CaseSensitive
    )
    $Text | Select-String -Pattern $RegEx -AllMatches -CaseSensitive:$CaseSensitive | ForEach-Object {$_.Matches.Value}
}
Function Get-NetIPAdapters {
    Param(
    [Parameter(Mandatory = $false)]
        [String[]]$ComputerName
    )
    if ($ComputerName.length -lt 1 -or $computername.Count -lt 1) {
        $computername = @($env:COMPUTERNAME)
    }
    $OutPut = @()
    #Vis netkort med tilhørende IP adr.
    foreach ($pc in $Computername) {
        $OutPut += Get-NetAdapter -CimSession $pc | Select-Object Name,InterfaceDescription,IfIndex,Status,MacAddress,LinkSpeed,@{N="IPv4";E={(Get-NetIpaddress -CimSession $pc -InterfaceIndex $_.ifindex -AddressFamily IPv4 ).IPAddress}},@{N="IPv6";E={(Get-NetIpaddress -CimSession $pc -InterfaceIndex $_.ifindex -AddressFamily IPv6 ).IPAddress}},@{N="Computer";E={$pc}} | Sort-Object -Property Name
    }
    $OutPut
}

Function Get-NthDayOfMonth {
    <#
    .SYNOPSIS
    Returns the Nth weekday of a specified month
    

    .DESCRIPTION
    Returns the Nth weekday of a specified month.
    If no weekday is specified an array is returned containing dates for the 7 weekdays throughout the specified month.
    If no Month or Year is specified current month will be used.

    .PARAMETER Month
    The month to process, in numeric format. If no month is specified current month is used.

    .PARAMETER Weekday
    The weekday to lookup. If no weekday is specified, all weekdays are returned.

    .PARAMETER Number
    The week number in the specified month. If no number is specified, all weekdays are returned.

    .PARAMETER Year
    The year to process. If no year is specified, current year is used.

    .INPUTS
    None. You cannot pipe objects to this function

    .OUTPUTS
    PSCustomObject

    .EXAMPLE
    PS> #Get the 3rd tuesday of march 1962
    PS> Get-NthDayOfMonth -Month 3 -Year 1962 -Weekday Tuesday -Number 3
           
    20. marts 1962 00:00:00
#>

[cmdletbinding()]
param (
    [validateset(1,2,3,4,5,6,7,8,9,10,11,12)]
    [int]$Month,
    [ValidatePattern("^[0-9]{4}$")]
    [int]$Year,
    [validateset("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")]
    [string]$Weekday,
    [validateset(-5,-4,-3,-2,-1,0,1,2,3,4,5)]
    $Number
)

if ($number) {
    [int]$number = $number #If parameter is cast as [int] in param section it will default to 0. If no type is defined null value is allowed, but any value will be string by default
}


#Find last date of current month. Workarounds to avoid any cultural differences (/,- or whatever as date seperator as well as mm/dd/yyyy, yyyy/dd/mm or whatever syntax)
$BaseDate = Get-Date
if ($Month) {
    $CurMonth = [int](Get-Date -Format MM)
    if ($CurMonth -ge $Month) {
        $BaseDate = (Get-Date $BaseDate).AddMonths(-($CurMonth - $Month))
    }
    else {
        $BaseDate = (Get-Date $BaseDate).AddMonths(($Month - $CurMonth))
    }
}

if ($Year) {
    $CurYear = [int](Get-Date -Format yyyy)
    if ($CurYear -ge $Year) {
        $BaseDate = (Get-Date $BaseDate).AddYears(-($CurYear - $Year))
    }
    else {
        $BaseDate = (Get-Date $BaseDate).AddYears(($Year - $CurYear))
    }
    
}

$CurDate = (Get-Date $BaseDate).Day
if ($CurDate -gt 1) {
    $FirstDate = (Get-Date $BaseDate).AddDays(-($CurDate -1)).Date
}
else {
    $FirstDate = (Get-Date $BaseDate).date
}
$NextMonth = (Get-Date $FirstDate).AddMonths(1)
$LastDate = (Get-Date $NextMonth).AddDays(-1)

# Build the object to get dates for each weekday
$Props = [ordered]@{"Monday" = @()
                    "Tuesday" = @()
                    "Wednesday" = @()
                    "Thursday" = @()
                    "Friday" = @()
                    "Saturday" = @()
                    "Sunday" = @()
                    }
$DaysOfMonth = New-Object -TypeName PSObject -Property $Props

#We start on day one and add the numeric values to parse through the dates
$DaysToProcess = @(0..($LastDate.Day - 1))
Foreach ($Day in $DaysToProcess) {
    $Date = (Get-Date $FirstDate).AddDays($Day)
    #Get dates corresponding the 7 weekdays
    $CurDayValue = $Date.DayOfWeek.value__
    if ($CurDayValue -eq 0) {
        $DaysOfMonth.Sunday += $Date
    }
    if ($CurDayValue -eq 1) {
        $DaysOfMonth.Monday += $Date
    }
    if ($CurDayValue -eq 2) {
        $DaysOfMonth.Tuesday += $Date
    }
    if ($CurDayValue -eq 3) {
        $DaysOfMonth.Wednesday += $Date
    }
    if ($CurDayValue -eq 4) {
        $DaysOfMonth.Thursday += $Date
    }
    if ($CurDayValue -eq 5) {
        $DaysOfMonth.Friday += $Date
    }
    if ($CurDayValue -eq 6) {
        $DaysOfMonth.Saturday += $Date
    }
}

$NumberWithinRange = ($number -ge -$DaysOfMonth.$Weekday.count -and $number -le ($DaysOfMonth.$Weekday.Count -1) -and -not [string]::IsNullOrWhiteSpace($number) )

if ($Weekday -and $NumberWithinRange) {
    if ($number -lt 0) {
        $number = $number 
    }
    else {
        $number = $number - 1
    }
    Return $DaysOfMonth.$Weekday[($number)]
}

if ($Weekday -and -not $NumberWithinRange -and -not [string]::IsNullOrWhiteSpace($number)) {
    Write-Warning "No $Weekday number $number in selected month" 
    break   
}

if ($Weekday) {
    Return $DaysOfMonth.$Weekday
}
if ($Number) {
    $Days = $DaysOfMonth | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name | Sort-Object
    foreach ($Day in $days) {
        #Recycle the $props from earlier with weekdays in correct order
        $props.$Day = $DaysOfMonth.$Day[($number -1)]
    }
    $Result = New-Object -TypeName PSObject -Property $props
    Return $Result
}

Return $DaysOfMonth
}
Function Get-StringASCIIValues {
[CMDLetbinding()]
    param (
        [string]$String
   )

   return $String.ToCharArray() | ForEach-Object {$_ + " : " + [int][Char]$_}
}

Function Get-StringHash {
    #https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-filehash?view=powershell-7.1 (ex. 4)
    [CMDLetBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string[]]$String,
        [Parameter(Mandatory = $false)]
        [ValidateSet("SHA1","SHA256","SHA384","SHA512","MACTripleDES","MD5","RIPEMD160")]
        [string]$Algorithm = "SHA256",
        [Parameter(Mandatory = $false)]
        [int]$GroupCount = 2,
        [Parameter(Mandatory = $false)]
        [String]$Seperator = "-"
    )

    $Result = @()
    Write-Verbose "Received $($String.count) string(s)"
    Write-Verbose "Using algorithm: $Algorithm"
    $stringAsStream = [System.IO.MemoryStream]::new()
    $writer = [System.IO.StreamWriter]::new($stringAsStream)
    foreach ($t in $String) {
        $writer.write($t)
        $writer.Flush()
        $stringAsStream.Position = 0
        $HashString = Get-FileHash -InputStream $stringAsStream -Algorithm $Algorithm | Select-Object -ExpandProperty Hash
        Write-Verbose "$($HashString.length) characters in hash"
    }

    Write-Verbose "Dividing string to groups of $GroupCount characters, seperated by $Seperator"
    for ($x = 0 ; $x -lt $HashString.Length ; $x = $x + $GroupCount) {
        $Result += $HashString[$x..($x + ($GroupCount -1))] -join ""
    }
    Write-Verbose "$($Result.count) groups"
    $Result = $Result -join $Seperator
    Write-Verbose "Returning $($Result.length) character string"

    return $Result
}

Function Get-Unicode {
    param(
        [string]$Word
    )
    $word.ToCharArray() | ForEach-Object {
        $_ + ": " + [int][char]$_ 
    }
}

Function Get-UserVariables {
    #Get, and display, any variable not defined in the $SysVars variable
    get-childitem variable: | Where-Object {$SysVars -notcontains $_.Name}
}

Function Get-WebRequestError {
<#
        .SYNOPSIS
        Read more detailed error from failed Invoke-Webrequest and Invoke-RestMethod
        https://stackoverflow.com/questions/35986647/how-do-i-get-the-body-of-a-web-request-that-returned-400-bad-request-from-invoke

        .Parameter ErrorObject
        $_ from a Catch block

    #>


    [CMDLetbinding()]
    param (
        [object]$ErrorObject
    )

    $streamReader = [System.IO.StreamReader]::new($ErrorObject.Exception.Response.GetResponseStream())
    $ErrResp = $streamReader.ReadToEnd() | ConvertFrom-Json
    $streamReader.Close()
    return $ErrResp
}

Function New-CSVExportable {
    param($Object
    )
    # Gennemgår properties for alle elementer, og tilføjer manglende så alle elementer har samme properties til CSV eksport eller lignende
    $AllMembers = @()
    foreach ($Item in $Object) {
        $ItemMembers = ($item | ConvertTo-Csv -NoTypeInformation -Delimiter ";")[0] -split ";" -replace '"','' #For at sikre vi får alle properties i den korrekte rækkefølge (Get-Member kan være lidt tilfældig i rækkefølgen)
        foreach ($itemmember in $ItemMembers) {
            if ($ItemMember -notin $AllMembers) {
                $AllMembers += $ItemMember
            }
        }
        
    }
    #$AllMembers = $AllMembers | Select-Object -Unique

    for ($x = 0 ; $x -lt $Object.Count ; $x++) {
        $CurMembers = $Object[$x] | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
        for ($y = 0 ; $y -lt $AllMembers.count ; $y++) {
            if ($AllMembers[$y] -notin $CurMembers) {
                $Object[$x] | Add-Member -MemberType NoteProperty -Name $AllMembers[$y] -Value "N/A"
            }
        }
    }
    return $Object

}

Function New-YAMLTemplate {
 
    <#
    .SYNOPSIS
    Generates Azure Pipelines based on the comment based help in the input script

    .Description
    Generates Azure Pipelines based on the comment based help in the input script.
    For help on comment based help see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help?view=powershell-7.2
    Script parameters are parsed, and YAML template, pipeline and variable files are generated with default values, and validateset values prepopulated.

    Default variables that will be defined in pipeline yaml:
        deployment: DeploymentDisplayName converted to lower-case, spaces replaced with underscores, and non-alphanumeric characters removed.
        deploymentDisplayName: Value of DeploymentDisplayName parameter

    For each supplied environment, default variables will be created:
        <ENV>_ServiceConnectionAD: '<ServiceConnection parameter value>'
        <ENV>_ServiceConnectionResources: '<ServiceConnection parameter value>'
        <ENV>_EnvironmentName: '<ENV>'

    Unless otherwise specified with the -Agent parameter, the template will use the 'Mastercard Payment Services' image by default.

    The script will output the following files:
        if -WikiOnly is not specified:
            <scriptname>.yml - the template for the script itself.
            deploy-<scriptname>.yml.sample - a sample pipeline yaml.
            deploy-<scriptname>-<environment>-vars.yml - a variable file for the <environment> stage of the pipeline file. One file for each environment specified in -Environment parameter
        if -WikiOnly, or -Wiki, is specified:
            <scriptname>.md - A Wiki file based on the comment based help.

    Outputfiles will be placed in the same directory as the source script, unless the -OutDir parameter is specified.
    The template for the script will have the extension .yml and the sample files will have the extension .yml.sample so the yaml selection list in Azure DevOps isn't crowded.


    .Parameter ScriptPath
    Path to script to generate YAML templates for

    .Parameter DeploymentDisplayName
    Display Name of deployment when pipeline is run. Will default to "Deployment of <scriptfile>"

    .Parameter Environment
    Name of environment(s) to deploy to. Will default to "Dev"

    .Parameter Overwrite
    Overwrite existing YAML files

    .Parameter ServiceConnection
    Name of serviceconnection. Will default to "IteraCCoEMG"

    .Parameter Wiki
    Generate Wiki file as well as template files.

    .Parameter WikiOnly
    Determines if only a Wiki should be generated.

    .Parameter OutDir
    Directory to output files to. If omitted file will be written to script location.

    .Parameter Agent
    Agent type to use when running pipeline

    .Example
    PS> $ScriptPath = "C:\Scripts\AwesomeScript.ps1"
    PS> New-YAMLTemplate -ScriptPath $ScriptPath -Environment "DEV","TEST" -Overwrite

    This will generate a template file, a pipeline file and two variable files for deployment of C:\Scripts\AwesomeScript.ps1 to DEV and TEST environments.
    Existing files will be overwritten, and files placed in C:\Scripts
    No Wiki file will be created.


    .Example
    PS> $ScriptPath = "C:\Scripts\AwesomeScript.ps1"
    PS> New-YAMLTemplate -ScriptPath $ScriptPath -Wiki -Environment Prod

    This will generate a template file, a pipeline file, a single varibles files for deployment of C:\Scripts\AwesomeScript.ps1 to Prod environment, as well as a Wiki file.
    If files already exist the script will return a message stating no files are generated.

    .Example
    PS> $ScriptPath = "C:\Scripts\AwesomeScript.ps1"
    PS> New-YAMLTemplate -ScriptPath $ScriptPath -WikiOnly -OutDir C:\Wikis -OverWrite

    This will generate a Wiki file only as C:\Wikis\AwesomeScript.md
    If the file already exist, it will be overwritten.

    #>


    [CMDLetbinding()]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateScript({ Get-ChildItem -File -Path $_ })]
        [String]$ScriptPath,
        [Parameter(Mandatory = $false)]
        [String]$DeploymentDisplayName = "Deployment of $(Split-Path -Path $ScriptPath -Leaf)",
        [Parameter(Mandatory = $false)]
        [String[]]$Environment = "Dev",
        [Parameter(Mandatory = $false)]
        [Switch]$Overwrite,
        [Parameter(Mandatory = $false)]
        [String]$ServiceConnection = "IteraCCoEMG",
        [Parameter(Mandatory = $false)]
        [switch]$WikiOnly,
        [Parameter(Mandatory = $false)]
        [switch]$Wiki,
        [Parameter(Mandatory = $false)]
        [ValidateScript({ Test-Path -Path $_ })]
        [String]$OutDir,
        [Parameter(Mandatory = $false)]
        [ValidateSet("Mastercard Payment Services", "vmImage: windows-latest", "vmImage: ubuntu-latest")]
        [String]$Agent 
    )

    # Pipeline PowerShell task: https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/powershell?view=azure-devops

    $ScriptName = Split-Path -Path $ScriptPath -Leaf
    $ScriptDirectory = Split-Path -Path $ScriptPath -Parent
    # This weird way of getting the file is necessary to get filesystem name casing. Otherwise whatever casing is passed in the parameter is used.
    # Should be obsolete after lower-case standards have been decided, except for producing a warning.
    $ScriptFile = Get-Item -Path "$ScriptDirectory\*.*" | Where-Object { $_.Name -eq $ScriptName }

    # Retrieve info from comment-based help and parameter definitions.
    $ScriptHelp                 = Get-Help -Name $ScriptPath -full 
    $ScriptCommand              = (Get-Command -Name $ScriptPath)
    $ScriptCommandParameters    = $ScriptCommand.Parameters
    $ScriptHelpParameters       = $ScriptHelp.parameters
    $ScriptBaseName             = $ScriptFile.BaseName
    $VariablePrefix             = $ScriptBaseName.replace("-", "_").ToLower()
    $ScriptExamples             = $ScriptHelp.Examples
    $ScriptSynopsis             = ($ScriptHelp.Synopsis | foreach-object { $_ | Out-String } ).split("`r`n") 
    $ScriptNotes                = if ($ScriptHelp.AlertSet.Alert.count -gt 0) { ($ScriptHelp.alertset.alert[0] | foreach-object { $_ | Out-String } ).split("`r`n") | ForEach-Object { if ( -not [string]::isnullorwhitespace($_)) { $_ } } }
    $ScriptDescription          = ($ScriptHelp.description | foreach-object { $_ | Out-String } ) -split ("`r`n") 
        
    # Header with a few reminderes, for the variables and pipeline files. soon-to-be obsolete when we all have become pipeline-gurus!
    $PipelineVariablesHeader = @()
    $PipelineVariablesHeader += '# If using double quotes, remember to escape special characters'
    $PipelineVariablesHeader += '# Booleans, and Numbers, must be passed in ${{variables.<variablename>}} to template to retain data type when received by template.'
    $PipelineVariablesHeader += '# Booleans still need to be prefixed with $ when passed to script, because Pipelines sucks (https://www.codewrecks.com/post/azdo/pipeline/powershell-boolean/)'
    $PipelineVariablesHeader += '# Split long strings to multiple lines by using >- , indenting value-lines ONE level and NO single-quotes surrounding entire value (https://yaml-multiline.info/ - (folded + strip))'


    # Get path of script relative to repo if possible.
    Push-Location -Path (Split-Path -Path $ScriptPath -Parent) -StackName RelativePath
    try {
        $RepoScriptPath = & git ls-files --full-name $ScriptPath
        if ([string]::IsNullOrWhiteSpace($RepoScriptPath)) {
            $RepoScriptPath = & git ls-files --full-name $ScriptPath --others
        }
            
        if ([string]::IsNullOrWhiteSpace($RepoScriptPath)) {
            # If we can't find the script as part of the repo, fallback to the path relative to current location
            $RepoScriptPath = (Resolve-Path -Path $ScriptPath -Relative).replace("\", "/")
            Write-Warning "Couldn't find path relative to repository. Is file in a repo? Relative references will fall back to $RepoScriptPath"
        }
        else {
            # We found the script as part of repo, so lets guess the project, repository and direct URL for the Wiki as well
            $RemoteGit          = & git remote -v # Returns something similar to 'origin https://<organization>@dev.azure.com/<organization>/<project>/_git/<repository> (push)'
            $RemoteURL          = "https://" + $RemoteGit.split(" ")[0].split("@")[-1] + "?path=/$RepoScriptPath"
            $RemotePath         = $RemoteGit[0].split("/")
            $DevOpsProject      = $RemotePath[4]
            $DevOpsRepository   = $RemotePath[6] -replace "\(fetch\)|\(push\)", ""
        }
    }
    catch {
        Write-Warning "Unable to run git commands"
        Write-Warning $_.Exception.Message 
    }
    Pop-Location -StackName RelativePath
        
    if ($RepoScriptPath -cmatch "[A-Z]") {
        # File names should be in lower case in accordance with https://dev.azure.com/itera-dk/Mastercard.PaymentsOnboarding/_git/infrastructure?path=/readme.md
        Write-Warning "Scriptpath not in all lowercase: $RepoScriptPath"
    }

    if ([string]::isnullorwhitespace($OutDir)) {
        [string]$OutDir = $ScriptFile.DirectoryName.ToString()
    }
    $FSTemplateFilePath     = Join-Path -Path $OutDir -ChildPath $ScriptFile.Name.Replace(".ps1", ".yml")
    $FSPipelineFilePath     = Join-Path -Path (Split-Path -Path $FSTemplateFilePath -Parent) -ChildPath ("deploy-$(Split-Path -Path $FSTemplateFilePath -Leaf)")
    $FSVariablesFilePath    = @{}
    foreach ($env in $environment.tolower()) {
        $FSVariablesFilePath[$env] = $FSPipelineFilePath.Replace(".yml", "-$($env)-vars.yml") #Template for variable files. #ENV# is replace with corresponding environment name.
    }
    $FSWikiFilePath = $FSTemplateFilePath.replace(".yml", ".md") 
    # Wiki uses dash'es for spaces, and hex values for dash'es, so replace those in the filename.
    $FSWikiFilePath = Join-Path (Split-Path -Path $FSWikiFilePath) -ChildPath ((Split-Path -Path $FSWikiFilePath -Leaf).Replace("-", "%2D").Replace(" ", "-"))

    # Get path to yaml template file, relative to script location
    $RepoTemplateFilePath   = $RepoScriptPath.replace(".ps1", ".yml")
    if ([string]::IsNullOrWhiteSpace((Split-Path -Path $RepoTemplateFilePath))) {
        # If script is located in root of repo, we cant split-path it
        $RepoPipelineFilePath  = "/deploy-$(Split-Path -Path $RepoTemplateFilePath -Leaf)"
    }
    else {
        $RepoPipelineFilePath   = "/" + (Join-Path -Path (Split-Path -Path $RepoTemplateFilePath) -ChildPath ("deploy-$(Split-Path -Path $RepoTemplateFilePath -Leaf)")).replace("\","/")
    }

    # Save variable filenames in hashtable for easy references
    $RepoVariablesFilePath  = @{}
    foreach ($env in $environment.tolower()) {
        $RepoVariablesFilePath[$env] = $RepoPipelineFilePath.Replace(".yml", "-$($env)-vars.yml") #Template for variable files. #ENV# is replace with corresponding environment name.
    }

    #$RepoWikiFilePath = $RepoTemplateFilePath.replace(".yml", ".md") # Maybe we'll need this one day.... maybe not


    # Parse the parameters and get necessary values for YAML generation
    $ScriptParameters = @()
    foreach ($param in $ScriptHelpParameters.parameter) {
        $Command    = $ScriptCommandParameters[$param.name]
        $Props      = [ordered]@{   "Description"                 = $param.description 
                                    "Name"                        = $param.name
                                    "HelpMessage"                 = ($Command.Attributes | Where-Object { $_.GetType().Name -eq "ParameterAttribute" }).HelpMessage
                                    "Type"                        = $param.type
                                    "Required"                    = $param.required
                                    "DefaultValue"                = $param.defaultValue
                                    "ValidateSet"                 = ($Command.Attributes | Where-Object { $_.GetType().Name -eq "ValidateSetAttribute" }).ValidValues
                                    "ValidateScript"              = ($Command.Attributes | Where-Object { $_.GetType().Name -eq "ValidateScriptAttribute" }).scriptblock
                                }

        # Build a description text to add to variables, and parameters, in YAML files
        $YAMLHelp = ""
        if ($props.Description.length -gt 0) {
            $YAMLHelp += "Description: $((($props.Description | foreach-object {$_.Text}) -join " ") -replace ("`r`n|`n|`r", " "))"
        }
        
        if ($Props.HelpMessage.Length -gt 0) {
            $YAMLHelp += " Help: $($Props.HelpMessage)"
        }

        $YAMLHelp += " Required: $($param.required)"

        if ($Props.ValidateSet.Count -gt 0) {
            $YAMLHelp += " ValidateSet: ($(($Props.ValidateSet | ForEach-Object {"'$_'"}) -join ","))"
        }

        if ($Props.ValidateScript.Length -gt 0) {
            $YAMLHelp += " ValidateScript: {$($Props.ValidateScript)}"
        }

        if ($YAMLHelp.Length -gt 0) {
            $Props.add("YAMLHelp", $YAMLHelp.Trim())
        }
        
        $ScriptParameters += New-Object -TypeName PSObject -Property $Props
    }

    if ($ScriptParameters.count -eq 0) {
        Write-Warning "No parameters found for $ScriptPath. Make sure comment based help is correctly entered: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help?view=powershell-7.2"
    }

    # Build the YAMLParameters object containing more YAML specific information (could be done in previous loop... to do someday)
    $YAMLParameters     = @()
    $ScriptArguments    = ""
    foreach ($param in $ScriptParameters) {
        $ParamType = $ParamDefaultValue = $null 
        # There are really only 3 parameter types we can use when running Powershell in a pipeline
        switch ($Param.Type.Name ) {
            "SwitchParameter"                                   { $ParamType = "boolean" }
            { $_ -match "Int|Int32|long|byte|double|single" }   { $ParamType = "number" }
            default                                             { $ParamType = "string" } # Undeclared parameters will be of type Object and treated as string
        }

        # Not a proper switch, but this is where we figure out the correct default value
        switch ($Param.DefaultValue) {
            { $_ -match "\$" }                                                                          { $ParamDefaultValue = "'' # Scriptet default: $($Param.DefaultValue)" ; break } # If default value contains $ it most likely references another parameter.
            { (-not ([string]::IsNullOrWhiteSpace($Param.DefaultValue)) -and $ParamType -eq "String") } { $ParamDefaultValue = "'$($param.defaultValue)'" ; break } # Add single quotes around string values
            { $ParamType -eq "number" }                                                                 { $ParamDefaultValue = "$($param.defaultValue)" ; break } # No quotes around numbers as that would make it a string
            { $ParamType -eq "boolean" }                                                                { if ($param.defaultvalue -eq $true) { $ParamDefaultValue = "true" } else { $ParamDefaultValue = "false" } ; break } # Set a default value for booleans as well
            { $Param.ValidateSet.count -gt 0 }                                                          { if ($Param.ValidateSet -contains " ") { $ParamDefaultValue = "' '" } else { $ParamDefaultValue = "'$($Param.ValidateSet[0])'" } }
            default                                                                                     { $ParamDefaultValue = "''" } # If all else fails, set the default value to empty string
        }

        $YAMLParameterProps = @{"Name"          = $Param.name
                                "YAMLHelp"      = $Param.YAMLHelp
                                "Type"          = $ParamType
                                "Default"       = $ParamDefaultValue
                                "ValidateSet"   = $param.validateSet 
                                "VariableName"  = "$($VariablePrefix)_$($param.name)" # Property to use as variable name in YAML. #ENV# will be replaced with the different environments to deploy to
                                }
        $YAMLParameters += New-Object -TypeName PSObject -Property $YAMLParameterProps

        # Define the scriptarguments to pass to the script. The name of the variable will correspond with the name of the parameter
        if ($ParamType -eq "boolean") {
            $ScriptArguments += ("-$($Param.Name):`$`${{parameters.$($Param.name)}} ") # Add additional $ to turn "false" into "$false"
        }
        elseif ($param.type.name -eq "String") {
            $ScriptArguments += ("-$($Param.Name) '`${{parameters.$($Param.name)}}' ") # Make sure string values has single quotes around them so spaces and special characters survive
        } 
        else {
            #integer type
            $ScriptArguments += ("-$($Param.Name) `${{parameters.$($Param.name)}} ") # Numbers as-is
        } 
        if ($YAMLParameters[-1].VariableName.Length -gt $MaxParameterNameLength) {
            $MaxParameterNameLength = $YAMLParameters[-1].VariableName.Length # Used for padding in pipeline and variables file, to make them less messy.
        }
    } 
    $MaxParameterNameLength++ # To account for the colon in the YAML

    # Initialize PipelineVariables and set the corresponding template as comment
    # $PipelineVariables contains the content of the variable files for each environment
    $PipelineVariables = @()
    $PipelineVariables += " # $(Split-Path -Path $RepoTemplateFilePath -leaf)"

    # Default template parameters independent of script parameters
    $TemplateParameters = @()
    $TemplateParameters += " - name: serviceConnection # The name of the service Connection to use"
    $TemplateParameters += " type: string"
    $TemplateParameters += " default: false"

    # Build the template parameters
    foreach ($param in $YAMLParameters) {
        $TemplateParameters += ""
        $TemplateParameters += " - name: $($param.Name) # $($Param.YAMLHelp)"
        $TemplateParameters += " type: $($Param.type)"
        $TemplateParameters += " default: $($Param.Default)"
        if ($param.validateset) {
            $TemplateParameters += " values:"
            foreach ($value in $param.validateset) {
                if ($param.Type -eq "number") {
                    $TemplateParameters += " - $value"
                }
                else {
                    $TemplateParameters += " - '$value'"
                }
            }
        }
        $PipelineVariables += " $("$($Param.VariableName):".PadRight($MaxParameterNameLength)) $($param.Default) # $($Param.YAMLHelp)"
    }

    #region BuildTemplate
    $Template = @()
    $Template += "# Template to deploy $($ScriptFile.Name):"

    # Add script synopsis to template file if available - could propably be done with out-string or similar waaaay simpler
    if ($ScriptHelp.Synopsis) {
        if ($ScriptSynopsis.length -gt 0) {
            $Template += "# Synopsis:"
            foreach ($line in $ScriptSynopsis) {
                $SplitLine = $Line.Trim().Split([Environment]::NewLine)
                foreach ($subline in $SplitLine) {
                    $Template += "#`t" + $subline
                }
            }
        }
    }
    $Template += ""
    # Add script description to template file if available
    if ($ScriptHelp.description) {
        if ($ScriptDescription.length -gt 0) {
            $Template += "# Description:"
            foreach ($line in $ScriptDescription) {
                # For some reason Description and Notes starts with an empty line
                $SplitLine = $line.trim().split([Environment]::NewLine)
                foreach ($subline in $SplitLine) {
                    $Template += "#`t" + $subline
                }
            }
        }
    }
    $Template += ""
    # Add script notes to template file if available
    if ($Scripthelp.Alertset) {
        if ($ScriptNotes.length -gt 0) {
            $Template += "# Notes:"
            # For some reason Description and Notes starts with an empty line
            $SplitNotes = $ScriptNotes.Trim().split([Environment]::NewLine)
            foreach ($line in $SplitNotes) {
                $Template += "#`t" + $line
            }
        }
    }

    $Template += ""
    $Template += "parameters:"
    $Template += $TemplateParameters
    $Template += ""
    $Template += "steps:"
    $Template += " - task: AzurePowerShell@5"
    $Template += " displayName: ""PS: $($ScriptFile.Name)"""
    $Template += " inputs:"
    $Template += ' azureSubscription: "${{parameters.serviceConnection}}"'
    $Template += ' scriptType: "FilePath"'
    $Template += " scriptPath: ""$RepoScriptPath"" # Relative to repo root"
    $Template += " azurePowerShellVersion: latestVersion"
    $Template += " scriptArguments: $ScriptArguments"
    $Template += " pwsh: true # Run in PowerShell Core"
    #endregion #BuildTemplate

    # Make variables nicely alligned
    $MaxEnvLength = $Environment | Group-Object -Property Length | Sort-Object -Property Name -Descending | Select-Object -First 1 -ExpandProperty Name
    $PadTo = "_ServiceConnectionResources".Length + $MaxEnvLength + " ".Length
        
    #region BuildPipeline
    $Pipeline = @()
    $Pipeline += "# https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema/?view=azure-pipelines"
    $Pipeline += ""
    $Pipeline += "trigger: none"
    $Pipeline += ""
    $Pipeline += $PipelineVariablesHeader
    $Pipeline += "variables:"
    $Pipeline += " # Pipeline variables"
    $Pipeline += " $("deployment:".PadRight($PadTo)) '$((($DeploymentDisplayName.ToCharArray() | Where-Object {$_ -match '[\w| ]'}) -join '').replace(" ","_").tolower())' `t`t# Name of deployment"
    $Pipeline += " $("deploymentDisplayName:".PadRight($PadTo)) '$DeploymentDisplayName' `t# Name of deployment"
    foreach ($env in $Environment) {
        $Pipeline += ""
        $Pipeline += " $("$($env)_ServiceConnectionAD:".PadRight($PadTo)) '$($ServiceConnection)' `t`t# Name of connection to use for AD deployments in $env environment"
        $Pipeline += " $("$($env)_ServiceConnectionResources:".PadRight($PadTo)) '$($ServiceConnection)' `t`t# Name of connection to use for Azure resource deployments in $env environment"
        $Pipeline += " $("$($env)_EnvironmentName:".PadRight($PadTo)) '$env'"
    }


    $Pipeline += ""
    $Pipeline += "# Variable file locations:"
    foreach ($env in $environment) {
        $Pipeline += "# $("$($env):".PadRight($MaxEnvLength)) $($RepoVariablesFilePath[$env])"
    }


    $Pipeline += ""
    $Pipeline += "# Comment/remove incorrect agents"
    $Pipeline += "pool:"
    if ($Agent) {
        $Pipeline += " $Agent"
    }
    else {
        $Pipeline += " 'Mastercard Payment Services'"
        $Pipeline += " #vmImage: windows-latest"
        $Pipeline += " #vmImage: ubuntu-latest"
    }
    $Pipeline += ""
    $Pipeline += "stages:"
    foreach ($env in $Environment) {
        $Pipeline += "# $env"
        $Pipeline += " - stage: `${{variables.$($env)_EnvironmentName}}"
        $Pipeline += " displayName: '`${{variables.$($env)_EnvironmentName}}'"

        $Pipeline += " variables:"
        $Pipeline += " - template: $($RepoVariablesFilePath[$env])"

        $Pipeline += " jobs:"
        $Pipeline += " - deployment: `${{variables.deployment}}"
        $Pipeline += " displayName: `${{variables.deploymentDisplayName}}"
        $Pipeline += " environment: `${{variables.$($env)_EnvironmentName}}"
        $Pipeline += " strategy:"
        $Pipeline += " runOnce:"
        $Pipeline += " deploy:"
        $Pipeline += " steps:"
        $Pipeline += " - checkout: self"
        $Pipeline += " - template: ""/$RepoTemplateFilePath"" #Template paths should be relative to the file that does the including. For absolute path use /path/to/template"
        $Pipeline += " parameters:"
        $Pipeline += " #serviceConnection: `$`{{variables.$($env)_ServiceConnectionAD}} # Comment/remove the incorrect connection" 
        $Pipeline += " serviceConnection: `$`{{variables.$($env)_ServiceConnectionResources}}"
        foreach ($param in $YAMLParameters) {
            $ParamValue = "`${{variables.$($param.VariableName)}}"
            $Pipeline += " $("$($param.Name):".PadRight($MaxParameterNameLength)) $ParamValue"
        }
        $Pipeline += ""
    }
    #endregion BuildPipeline

    #Finally output the files
    try {
        if ($Wiki -or $WikiOnly) {
            $ScriptWiki = @("<b>Name:</b> $(Split-Path $ScriptPath -Leaf)"
                ""
                "<b>Project:</b> $DevOpsProject"
                ""
                "<b>Repository:</b> $DevOpsRepository"
                ""
                "<b>Path:</b> <a href=""$RemoteURL""> $RepoScriptPath</a>"
                ""
                "<b>Synopsis:</b>"
                $ScriptSynopsis
                ""
                "<b>Description:</b>"
                $ScriptDescription
                ""
                if ($ScriptNotes.Length -gt 0) {
                    "<b>Notes:</b>"
                    $ScriptNotes
                    ""
                }
                "<b>Examples</b>"
                ($ScriptExamples | Out-String).Trim()
                ""
                "<b>Parameters</b>"
                ($ScriptHelpParameters | Out-String).split("`r`n") | ForEach-Object {$_.trim()}
            ) -join "`r`n"
            $ScriptWiki | Out-File -FilePath $FSWikiFilePath -Encoding utf8 -NoClobber:(-not $Overwrite) -Force:$Overwrite
        }
        if (-not $WikiOnly) {
            $PipelineVariablesHeader += "variables:"
            $PipelineVariables = $PipelineVariablesHeader + $PipelineVariables
            foreach ($env in $Environment) {
                $PipelineVariables | Out-File -FilePath "$($FSVariablesFilePath[$Env]).sample" -Encoding utf8 -NoClobber:(-not $Overwrite) -Force:$Overwrite
            }
            $Pipeline   | Out-File -FilePath "$FSPipelineFilePath.sample" -Encoding utf8 -NoClobber:(-not $Overwrite) -Force:$Overwrite
            $Template   | Out-File -FilePath $FSTemplateFilePath -Encoding utf8 -NoClobber:(-not $Overwrite) -Force:$Overwrite
        }
    }
    catch {
        Write-Error "Unable to write files"
        Write-Error $_.Exception.Message 
    }
}


Function Prompt {
    (get-date -Format HH:mm:ss).ToString().Replace(".",":") + " PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ";
    # .Link
    # https://go.microsoft.com/fwlink/?LinkID=225750
    # .ExternalHelp System.Management.Automation.dll-help.xml
}

Function Remove-OldModules {
[ CMDLetbinding()]
  Param ()

  $Modules = Get-ChildItem "$($ENV:ProgramFiles)\WindowsPowerShell\Modules" | Where-Object {$_.mode -match "^d"} 
  foreach ($Module in $Modules) {
    Write-Host "Removing old versions of $($Module.Name)"
    $Versions = Get-ChildItem -Path $Module.FullName | Sort-Object -Property Name -Descending
    $LastVersion =  $Versions | Select-Object -First 1
    $OldVersions =  @($Versions | Where-Object {$_ -ne $LastVersion})
    Remove-Module -Name $Module.Name -Force -Confirm:$false -ErrorAction SilentlyContinue
    if ($OldVersions.count -gt 0) {
        Write-Host "`t$($OldVersions.Count) old versions found"
        try {
            $OldVersions | Remove-Item -Recurse -Force -ErrorAction Stop
            Write-Host "`tRemoved"
        }
        catch {
            Write-Warning "`tCouldn't remove old versions: $($_.Exception.Message)"
        }
    }
    else {
        Write-Host "`tNo old versions found"
    }
  }
}

Function Set-AzTestSetup {

    [CMDLetbinding()]
    param(
        [Parameter(Mandatory =$true)]
        [String[]]$ResourceGroupName,
        [string]$Prefix,
        [int]$NumWinVMs,
        [int]$NumLinuxVMs,
        [string]$VMAutoshutdownTime,
        [string]$WorkspaceName,
        [string]$AutomationAccountName,
        [String]$Location,
        [string]$KeyvaultName,
        [switch]$PowerOff,
        [switch]$Force,
        [switch]$Remove

    )
    foreach ($RG in $ResourceGroupName) {
        if (-not $PSBoundParameters.ContainsKey("Prefix")) {[string]$Prefix = $RG}
        if (-not $PSBoundParameters.ContainsKey("NumWinVMs")) {[int]$NumWinVMs = 2}
        if (-not $PSBoundParameters.ContainsKey("NumLinuxVMs")) {[int]$NumLinuxVMs = 0}
        if (-not $PSBoundParameters.ContainsKey("VMAutoshutdownTime")) {[string]$VMAutoshutdownTime = "2300"}
        if (-not $PSBoundParameters.ContainsKey("WorkspaceName")) {[string]$WorkspaceName = ($Prefix + "-workspace")}
        if (-not $PSBoundParameters.ContainsKey("AutomationAccountName")) {[string]$AutomationAccountName = ($Prefix + "-automation")}
        if (-not $PSBoundParameters.ContainsKey("Location")) {[String]$Location = "westeurope"}
        if (-not $PSBoundParameters.ContainsKey("KeyvaultName")) {[string]$KeyvaultName = ($Prefix + "-keyvault")}

        try {
            if (Get-AzResourceGroup -Name $RG -ErrorAction SilentlyContinue) {
                Write-Host "$RG exist"
                if ($Force -or $Remove) {
                    Write-Host "`tWill be deleted"
                    $WorkSpace = Get-AzOperationalInsightsWorkspace -ResourceGroupName $RG -Name $WorkspaceName -ErrorAction SilentlyContinue
                    $Keyvault = Get-AzKeyVault -VaultName $KeyvaultName -ResourceGroupName $RG -ErrorAction SilentlyContinue
                    if ($null -eq $Keyvault) {
                        $keyvault = Get-AzKeyVault -VaultName $KeyvaultName -InRemovedState -Location $location 
                        if ($null -ne $Keyvault) {
                            Write-Host "`tDeleting $KeyvaultName"
                            $null = Remove-AzKeyVault -VaultName $KeyvaultName -InRemovedState -Force -Confirm:$false -Location $Location
                        }
                    }
                    else {
                        Write-Host "`tDeleting $KeyvaultName"
                        Remove-AzKeyVault -VaultName $KeyvaultName -Force -Confirm:$false -Location $location
                        Start-Sleep -Seconds 1 
                        Remove-AzKeyVault -VaultName $KeyvaultName -InRemovedState -Force -Confirm:$false -Location $location
                    }
                    if ($WorkSpace) {
                        Write-Host "`tDeleting Workspace"
                        $workspace | Remove-AzOperationalInsightsWorkspace -ForceDelete -Force -Confirm:$false 
                    }
                    Write-Host "`tDeleting Resourcegroup and contained resources"
                    Remove-AzResourceGroup -Name $RG -Force -Confirm:$false
                }
                else {
                    Write-Host "Nothing to do"
                    continue
                }
            }
            if ($Remove) {
                Write-Host "Remove specified. Exiting"
                continue 
            }

            Write-Host "Creating $RG"
            New-AzResourceGroup -Name $RG -Location $Location 
            Write-Host "Creating $AutomationAccountName"
            New-AzAutomationAccount -ResourceGroupName $RG -Name $AutomationAccountName -Location $Location -Plan Basic -AssignSystemIdentity 
            Write-Host "Creating $KeyvaultName"
            New-AzKeyVault -Name $KeyvaultName -ResourceGroupName $RG -Location $Location -EnabledForDeployment -EnabledForTemplateDeployment -EnabledForDiskEncryption -SoftDeleteRetentionInDays 7 -Sku Standard 
            Set-AzKeyVaultAccessPolicy -VaultName $KeyvaultName -ResourceGroupName $RG -UserPrincipalName "robert.eriksen_itera.com#EXT#@roedomlan.onmicrosoft.com" -PermissionsToKeys all -PermissionsToSecrets all -PermissionsToCertificates all -PermissionsToStorage all -Confirm:$false 
            Set-AzKeyVaultAccessPolicy -VaultName $KeyvaultName -ResourceGroupName $RG -ObjectId (Get-AzAutomationAccount -ResourceGroupName $RG -Name $AutomationAccountName).Identity.PrincipalId -PermissionsToKeys all -PermissionsToSecrets all -PermissionsToCertificates all -PermissionsToStorage all -Confirm:$false 
            Set-AzKeyVaultAccessPolicy -VaultName $KeyvaultName -ResourceGroupName $RG -ServicePrincipalName 04e7eb7d-da63-4c13-b5ba-04331145fdff -PermissionsToKeys all -PermissionsToSecrets all -PermissionsToCertificates all -PermissionsToStorage all -Confirm:$false 
            Write-Host "Creating $WorkspaceName"
            New-azOperationalInsightsWorkspace -ResourceGroupName $RG -Name $WorkspaceName -Location $location -Sku pergb2018
            $VMCredentials = [pscredential]::new("roe",("Pokemon1234!" | ConvertTo-SecureString -AsPlainText -Force))
            # https://www.powershellgallery.com/packages/HannelsToolBox/1.4.0/Content/Functions%5CEnable-AzureVMAutoShutdown.ps1
            $ShutdownPolicy = @{}
            $ShutdownPolicy.Add('status', 'Enabled')
            $ShutdownPolicy.Add('taskType', 'ComputeVmShutdownTask')
            $ShutdownPolicy.Add('dailyRecurrence', @{'time'= "$VMAutoshutdownTime"})
            $ShutdownPolicy.Add('timeZoneId', "Romance Standard Time")
            $ShutdownPolicy.Add('notificationSettings', @{status='enabled'; timeInMinutes=30; emailRecipient="robert.eriksen@itera.com" })
            $VMPrefix = "$($RG[0])$($RG[-1])"
            if ($NumWinVMs -gt 0) {
                (1..$NumWinVMs) | ForEach-Object {
                    $VMName = ([string]"$($VMPrefix)-Win-$( $_)")
                    Write-Host "Deploying $VMName"
                    $null = New-AzVm -ResourceGroupName $RG -Name $VMName -Location $Location -Credential $VMCredentials -VirtualNetworkName "$($RG)-vnet" -SubnetName "$($RG)-Subnet" -SecurityGroupName "$($RG)-nsg" -PublicIpAddressName "$($VMName)-Public-ip" -OpenPorts 80,3389 -Size "Standard_B2s" -Image Win2019Datacenter 
                    $vm = Get-AzVM -ResourceGroupName $RG -Name $VMName 
                    $vm | Stop-AzVM -Confirm:$false -Force 
                    $Disk = Get-AzDisk | Where-Object {$_.ManagedBy -eq $vm.id}
                    $Disk.Sku = [Microsoft.Azure.Management.Compute.Models.DiskSku]::new("Standard_LRS")
                    $disk | Update-AzDisk
                    $rgName = $vm.ResourceGroupName
                    $vmName = $vm.Name
                    $location = $vm.Location
                    $VMResourceId = $VM.Id
                    $SubscriptionId = ($vm.Id).Split('/')[2]
                    $ScheduledShutdownResourceId = "/subscriptions/$SubscriptionId/resourceGroups/$rgName/providers/microsoft.devtestlab/schedules/shutdown-computevm-$vmName"
                    if ($VMAutoshutdownTime -ne "Off") {
                        Write-Host "Setting autoshutdown: $VMAutoshutdownTime"
                        $ShutdownPolicy['targetResourceId'] = $VMResourceId
                        $null = New-azResource -Location $location -ResourceId $ScheduledShutdownResourceId -Properties $ShutdownPolicy -Force  
                    }
                    if (-not $PowerOff) {
                        Write-Host "Starting VM"
                        $vm | Start-AzVM
                    }
                }
            }
            if ($NumLinuxVMs -gt 0) {
                (1..$NumLinuxVMs) | ForEach-Object {
                    $VMName = ([string]"$($VMPrefix)-Lin-$($_)")
                    Write-Host "Deploying $VMName"
                    $null = New-AzVm -ResourceGroupName $RG -Name $VMName -Location $Location -Credential $VMCredentials -VirtualNetworkName "$($RG)-vnet" -SubnetName "$($RG)-Subnet" -SecurityGroupName "$($RG)-nsg" -PublicIpAddressName "$($VMName)-Public-ip" -OpenPorts 80,3389 -Size "Standard_B2s" -Image UbuntuLTS
                    $vm = Get-AzVM -ResourceGroupName $RG -Name $VMName 
                    $vm | Stop-AzVM -Confirm:$false -Force 
                    $Disk = Get-AzDisk | Where-Object {$_.ManagedBy -eq $vm.id}
                    $Disk.Sku = [Microsoft.Azure.Management.Compute.Models.DiskSku]::new("Standard_LRS")
                    $disk | Update-AzDisk
                    $rgName = $vm.ResourceGroupName
                    $vmName = $vm.Name
                    $location = $vm.Location
                    $VMResourceId = $VM.Id
                    $SubscriptionId = ($vm.Id).Split('/')[2]
                    $ScheduledShutdownResourceId = "/subscriptions/$SubscriptionId/resourceGroups/$rgName/providers/microsoft.devtestlab/schedules/shutdown-computevm-$vmName"
                    if ($VMAutoshutdownTime -ne "Off") {
                        Write-Host "Setting autoshutdown: $VMAutoshutdownTime"
                        $ShutdownPolicy['targetResourceId'] = $VMResourceId
                        $null = New-azResource -Location $location -ResourceId $ScheduledShutdownResourceId -Properties $ShutdownPolicy -Force  
                    }
                    if (-not $PowerOff) {
                        Write-Host "Starting VM"
                        $vm | Start-AzVM
                    }
                }
            }
        }
        catch {
            throw $_ 
        }
    }
}

Function Set-SystemVariables {
    #Collect all variables and store them, so userdefined variables can be easily cleared without restarting the PowerShell session
    New-Variable -Name 'SysVars' -Scope 'Global' -Force
    $global:SysVars = Get-Variable | Select-Object -ExpandProperty Name
    $global:SysVars += 'SysVars'
}


        ############ run functions on PS startup ############
        $ProfilePath = $profile.CurrentUserAllHosts
        $ProfileContent = Get-Content -Path $ProfilePath 
        if (-not ($ProfileContent.Where({$_.trim() -match "^Set-SystemVariables"}))) {
            Write-Host "Module roeprofile: First Run - Adding Set-SystemVariables to $profilepath"
            @(
                $ProfileContent
                '# Added by module: roeprofile'
                '# Stores default variable-names in $SysVars so any variables created in a session can be cleared using Clear-UserVariables'
                "Set-SystemVariables"
            ) | Set-Content -Path $ProfilePath
        }

        if (-not ($ProfileContent.Where({$_.trim() -match "^Prompt"}))) {
            Write-Host "Module roeprofile: First Run - Adding Prompt to $profilepath"
            @(
                $ProfileContent
                '# Added by module: roeprofile'
                '# Adds timestamp to prompt'
                "Prompt"
            ) | Set-Content -Path $ProfilePath
        }