ARMDeploy.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
Using Namespace Microsoft.Azure.Commands.Management.Storage.Models
Using Namespace Microsoft.Azure.Commands.Network.Models

<#
LICENSE:
The MIT License (MIT)
Copyright (c) 2020 Preston K. Parsard
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
DISCLAIMER:
THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. We grant You a nonexclusive,
royalty-free right to use and modify the Sample Code and to reproduce and distribute the Sample Code, provided that You agree: (i) to not use Our name,
logo, or trademarks to market Your software product in which the Sample Code is embedded;
(ii) to include a valid copyright notice on Your software product in which the Sample Code is embedded; and (iii) to indemnify, hold harmless,
and defend Us and Our suppliers from and against any claims or lawsuits, including attorneys’ fees,
that arise or result from the use or distribution of the Sample Code.
 
LINKS
1. https://docs.microsoft.com/en-us/powershell/scripting/gallery/how-to/working-with-local-psrepositories?view=powershell-7
#>

function New-ARMDeployHeader
{
<#
.SYNOPSIS
 Create a new script header for console and log output.
.DESCRIPTION
 This function will create a new header label with a title for the script.
.EXAMPLE
 Create a new header hashtable with a title of 'TEST' and two line separators; single and double.
 New-ARMDeployHeader -label TEST -charCount 80
 Name Value
 ---- -----
 Title TEST : 01/21/2020 18:16:20
 SeparatorSingle --------------------------------------------------------------------------------
 SeparatorDouble ================================================================================
.PARAMETER label
 The title that will be used for the script
.PARAMATER charCount
 The number of characters representing the width of the header, using the "=" character as a header separator.
.INPUTS
 None
.OUTPUTS
 [hashtable]$header
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Header
.LINK
 https://www.powershellgallery.com/packages/ARMDeploy
#>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param (
        [Parameter(Mandatory = $true)]
        [string]$label,
        [Parameter(Mandatory = $true)]
        [int]$charCount
    ) # end param

    $header = @{
        # Draw double line
        SeparatorDouble = ("=" * $charCount)
        Title = ("$label :" + " $(Get-Date)")
        # Draw single line
        SeparatorSingle = ("-" * $charCount)
    } # end hashtable
    return $header
} # end function
function Get-ARMDeployPSModule
{
<#
.SYNOPSIS
 Install PowerShell modules from a specified repository.
.DESCRIPTION
 This function installs a set of PowerShell or PowerShell DSC resource modules from a designated PowerShell (NuGet) repository.
 The repository can be a local or online repository, such as \\<server>\<share>\modules or https://www.powershellgallery.com.
 You can even use Azure Artifacts (For more details, see link 2 in the LINK tag below).
 This function will check if the locally installed version of a repository is older than the current online version. In this case, the module will be updated to the most recent online version.
 Since this function performs module auto-updating, if a specific version must be used for backward compatibility, this function should not be used. Instead use the Install-Module cmdlet with the -RequiredVersion parameter.
.EXAMPLE
 This example shows installing two modules; 'WriteToLogs' and 'xActiveDirectory' installed from the online public PSGallery repository.
 $modules = @('WriteToLogs','xActiveDirectory')
 Get-ARMDeployPSModule -ModulesToInstall $modules -PSRepository 'PSGallery' -Verbose
 
 VERBOSE: Using the provider 'Bootstrap' for searching packages.
 VERBOSE: Finding the package 'Bootstrap::FindPackage' 'Nuget','','','''.
 VERBOSE: Installing the package 'https://onegetcdn.azureedge.net/providers/nuget-2.8.5.208.package.swidtag'.
 VERBOSE: Installed the package 'nuget' to 'C:\Program Files\PackageManagement\ProviderAssemblies\nuget\2.8.5.208\Microsoft.PackageManagement.NuGetProvider.dll'.
 VERBOSE: Acquiring providers for assembly: C:\Program Files\PackageManagement\ProviderAssemblies\nuget\2.8.5.208\Microsoft.PackageManagement.NuGetProvider.dll
 VERBOSE: Skipping previously processed provider 'NuGet'.
 
 Name Version Source Summary
 ---- ------- ------ -------
 nuget 2.8.5.208 https://onege... NuGet provider for the OneGet meta-package manager
 VERBOSE: Importing the package provider Nuget
 VERBOSE: The provider 'NuGet' has already been imported. Trying to import it again.
 VERBOSE: Importing package provider 'NuGet'.
 VERBOSE: Imported provider 'C:\Program Files\PackageManagement\ProviderAssemblies\nuget\2.8.5.208\Microsoft.PackageManagement.NuGetProvider.dll' .
 VERBOSE: Checking for updates for module 'WriteToLogs'.
 VERBOSE: Repository details, Name = 'PSGallery', Location = 'https://www.powershellgallery.com/api/v2'; IsTrusted = 'True'; IsRegistered = 'True'.
 VERBOSE: Using the provider 'PowerShellGet' for searching packages.
 VERBOSE: Using the specified source names : 'PSGallery'.
 VERBOSE: Getting the provider object for the PackageManagement Provider 'NuGet'.
 VERBOSE: The specified Location is 'https://www.powershellgallery.com/api/v2' and PackageManagementProvider is 'NuGet'.
 VERBOSE: Searching repository 'https://www.powershellgallery.com/api/v2/FindPackagesById()?id='WriteToLogs'' for ''.
 VERBOSE: Total package yield:'1' for the specified package 'WriteToLogs'.
 VERBOSE: Performing the operation "Update-Module" on target "Version '1.1.1' of module 'WriteToLogs', updating to version '1.1.1'".
 VERBOSE: The installation scope is specified to be 'AllUsers'.
 VERBOSE: The specified module will be installed in 'C:\Program Files\WindowsPowerShell\Modules'.
 VERBOSE: The specified Location is 'NuGet' and PackageManagementProvider is 'NuGet'.
 VERBOSE: Downloading module 'WriteToLogs' with version '1.1.1' from the repository 'https://www.powershellgallery.com/api/v2'.
 VERBOSE: Searching repository 'https://www.powershellgallery.com/api/v2/FindPackagesById()?id='WriteToLogs'' for ''.
 VERBOSE: InstallPackage' <ommited for privacy>
 VERBOSE: DownloadPackage' - name= <omitted for privacy>
 VERBOSE: Completed downloading 'https://www.powershellgallery.com/api/v2/package/WriteToLogs/1.1.1'.
 VERBOSE: Completed downloading 'WriteToLogs'.
 VERBOSE: Hash for package 'WriteToLogs' does not match hash provided from the server.
 VERBOSE: InstallPackageLocal'
 VERBOSE: Validating the 'WriteToLogs' module contents under <omitted for privacy> path.
 VERBOSE: Test-ModuleManifest successfully validated the module manifest file <omitted for privacy>
 VERBOSE: Validating the authenticode signature and publisher of the catalog file or module manifest file of the module 'WriteToLogs'.
 VERBOSE: Catalog file 'WriteToLogs.cat' is not found in the contents of the module 'WriteToLogs' being installed.
 VERBOSE: For publisher validation, current module 'WriteToLogs' with version '1.1.1' with publisher name '' from root certificate authority ''. Is this module signed by Microsoft: 'False'.
 VERBOSE: For publisher validation, using the previously-installed module 'WriteToLogs' with version '1.1.1' under 'C:\Program Files\WindowsPowerShell\Modules\WriteToLogs\1.1.1' with publisher name '' from root certificate authority ''. Is this module signed by Microsoft: 'False'.
 VERBOSE: Checking for possible command collisions for the module 'WriteToLogs' commands.
 VERBOSE: Module 'WriteToLogs' was installed successfully to path 'C:\Program Files\WindowsPowerShell\Modules\WriteToLogs\1.1.1'.
.PARAMETER ModulesToInstall
 The modules to install.
.PARAMETER PSRepository
 The PowerShell repository from where modules will be installed or updated.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Modules
.LINK
 1: https://www.powershellgallery.com/packages/ARMDeploy
 2: https://docs.microsoft.com/en-us/azure/devops/artifacts/tutorials/private-powershell-library?view=azure-devops
#>

    [CmdletBinding(PositionalBinding = $false)]
    Param
    (
        # Required modules
        [Parameter(Mandatory = $true,
                   HelpMessage = "Please enter the PowerShellGallery.com modules required for this script",
                   ValueFromPipeline = $true,
                   Position = 0)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [string[]]$ModulesToInstall,
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [string]$PSRepository = "PSGallery"
    ) #end param

    Set-PSRepository -Name $PSRepository -InstallationPolicy Trusted
    Install-PackageProvider -Name Nuget -ForceBootstrap -Force
    foreach ($Module in $ModulesToInstall)
    {
        if (Get-InstalledModule -Name $Module -ErrorAction SilentlyContinue)
        {
            # If module exists, update it
            [string]$currentVersion = (Find-Module -Name $Module -Repository $PSRepository).Version
            [string]$installedVersion = (Get-InstalledModule -Name $Module).Version
            If ($currentVersion -ne $installedVersion)
            {
                # If this is a DSC Resource module, i.e. x, then completely uninstall the module and remove it before installing it
                If ($Module.Substring(0,1) -eq "x")
                {
                    Uninstall-Module -Name $Module -Force -ErrorAction SilentlyContinue -Verbose
                    Remove-Module -Name $Module -Force -ErrorAction SilentlyContinue -Verbose
                    Install-Module -Name $Module -Repository $PSRepository -Force -ErrorAction SilentlyContinue -Verbose
                } # end if
                # Otherwise just update it
                else
                {
                    # Update modules if required
                    Update-Module -Name $Module -Force -ErrorAction SilentlyContinue -Verbose
                } # end else
            } # end if
        } # end if
        # If the modules aren't already loaded, install and import it.
        else
        {
            Install-Module -Name $Module -Repository $PSRepository -Force -Verbose
            Import-Module -Name $Module -Verbose
        } #end If
    } #end foreach
} #end function
function Remove-ARMDeployPSModule
{
<#
.SYNOPSIS
 Removes a specified module from the current local machine.
.DESCRIPTION
 This function first checks to see if a particual module is currently installed on the local system, and if so, also uninstalls it and removes it from the current PowerShell session.
.EXAMPLE
 In this example, the AzureRM module will be removed from the local machine.
 Remove-ARMDeployModule -ModuleToRemove AzureRM -Verbose
.PARAMETER ModuleToRemove
 The module to remove.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Modules
.LINK
 1: https://www.powershellgallery.com/packages/ARMDeploy
 2: https://docs.microsoft.com/en-us/powershell/azure/new-azureps-module-az?view=azps-1.6.0
#>

    [CmdletBinding()]
    param
    (
        [string]$ModuleToRemove
    ) # end param
    # This is to avoid conflicts with installing the new Az modules since it's not recommended to have both installed on the same system. See LINK tag, item 2: in the comment based help section.
    if (Get-InstalledModule -Name $ModuleToRemove -ErrorAction SilentlyContinue -Verbose)
    {
        Uninstall-Module -Name $ModuleToRemove -ErrorAction SilentlyContinue -Verbose
        Remove-Module -Name $ModuleToRemove -ErrorAction SilentlyContinue -Verbose
    } # end if
} # end function
function New-ARMDeployDscArchive
{
<#
.SYNOPSIS
 Converts each DSC configuration script to a *.zip file
.DESCRIPTION
 This function will enumerate through a specified DSC source folder where DSC configuration scripts are located, and convert each script to a zip file.
 The *.ps1 configuration files must be converted to the *.zip format so they can be subsequently uploaded to Azure storage and referenced from within ARM templates for Azure deployment based DSC confiugrations.
.EXAMPLE
 In this example, a set of DSC artifacts will be archived, with each *.ps1 file converted to a *.zip file format.
 New-ARMDeployDscArchive -DscSourceFolder <DscSourceFolder> -Verbose
.PARAMETER DscSourceFolder
 The DSC source folder where the DSC artificats reside.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: DSC, Desired State Configuration, State Configuration
.LINK
 1: https://www.powershellgallery.com/packages/ARMDeploy
#>

    [CmdletBinding()]
    param
    (
        [ValidateScript({Test-Path -Path $_ -PathType Container})]
        [string]$DSCSourceFolder
    ) # end param
    $DSCSourceFilePaths = @(Get-ChildItem $DSCSourceFolder -File -Filter '*.ps1' | ForEach-Object -Process {$_.FullName})
    foreach ($DSCSourceFilePath in $DSCSourceFilePaths)
    {
        $DSCArchiveFilePath = $DSCSourceFilePath.Substring(0, $DSCSourceFilePath.Length - 4) + '.zip'
        Publish-AzVMDscConfiguration $DSCSourceFilePath -OutputArchivePath $DSCArchiveFilePath -Force -Verbose
    } # end foreach
} # end function

function Enter-ARMDeployFQDN
{
<#
.SYNOPSIS
 Obtains a registered fully qualified domain name for the ADDS domain that will be created from IaaS VMs in Azure.
.DESCRIPTION
 This function will prompt for an existing, registered fully qualified domain name. This domain name will be used as the domain in Azure using the IaaS deployment model when the domain controllers are provisioned.
 If the domain does not exist, the prompt for a valid, registered domain name will be re-generated.
.EXAMPLE
 Enter-ARMDeployFQDN
.INPUTS
 A prompt for a fully qualified domain name will be generated by the function.
.OUTPUTS
 [string]$DomainFQDN
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Active Directory, Domain, FQDN
.LINK
 1: https://www.powershellgallery.com/packages/ARMDeploy
#>

    [OutputType([string])]
    [CmdletBinding()]
    param()

    Do
    {
        [string]$DomainFQDN = Read-Host "Please enter your fully qualified domain name, i.e. [example.contoso.com] "
        $DomainFQDN = $DomainFQDN.ToLower()
    } #end Do
    Until (Resolve-DnsName -Name $DomainFQDN -ErrorAction SilentlyContinue)
    return $DomainFQDN
} # end function
function Push-ARMDeployArtifactsToAzureStorage
{
<#
.SYNOPSIS
 Pushes ARM artifacts to an Azure storage account container.
.DESCRIPTION
 This function will upload artifacts to a storage account container in Azure. The function is given a list of directories, the local file system based artifacts staging directory, the storage account resource object and the storage container name.
.EXAMPLE
 Push-ARMDeployArtifactsToAzureStorage -dirlist <dirList> -ArtifactsStagingDirectory <ArtifactsStagingDirectory> -StorageAccount <StorageAccount> -StorageContainerName <StorageContainerName> -Verbose
.PARAMETER dirList
 The list of directories that will be enumated for files with extensions of *.json, *.ps1, *.csv, *.zip to be uploaded to Azure storage.
.PARAMETER ArtifactsStagingDirectory
 The root file system directory from which artifict files will be discovered.
.PARAMETER StorageAccount
 The storage account resource object that will be used for staging the artifact files in Azure blob storage.
.PARAMETER StorageContainerName
 The storage container name within the storage account resource where the artifact files will be staged in Azure blob storage.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Active Directory, Domain, FQDN
.LINK
 1: https://www.powershellgallery.com/packages/ARMDeploy
#>

    [CmdletBinding()]
    param
    (
        [ValidateNotNull()]
        [string[]]$dirList,
        [string]$ArtifactsStagingDirectory,
        [PSStorageAccount]$StorageAccount,
        [string]$StorageContainerName
    ) # end param

    # Initialize internal variables
    $dir = $null
    $pathList = @()
    $filePaths = @()
    $SourcePath = $null
    $subStringStart = $null
    $subStringStop = $null

    # Build an array of directories that will be used to recursively copy the artifacts content to the new Azure storage account container.
    ForEach ($dir in $dirList)
    {
        if ($dir -eq $ArtifactsStagingDirectory)
        {
            $filePaths = Get-ChildItem -Path $dir -File -Recurse -Include *.json, *.ps1, *.csv, *.zip | ForEach-Object -Process {$_.FullName}
        } # end if
        else
        {
            $filePaths = Get-childItem -path $dir -File -Recurse | ForEach-Object -Process {$_.FullName}
        } # end else
        if ($filePaths)
        {
            $pathList += $filePaths
        } # end if
    } # end for each
    # Copy files to storage account
    # From local storage staging area to the storage account container
    New-AzStorageContainer -Name $StorageContainerName -Context $StorageAccount.Context -ErrorAction SilentlyContinue *>&1
    foreach ($SourcePath in $pathList)
    {
        $subStringStart = (Resolve-Path -Path $ArtifactsStagingDirectory).Path.Length + 1
        $subStringStop = ($SourcePath.Length - $subStringStart)

        Set-AzStorageBlobContent -File $SourcePath -Blob $SourcePath.Substring($subStringStart,$subStringStop) -Container $StorageContainerName -Context $StorageAccount.Context -Force
    } # end foreach
} # end function
function New-ARMDeployRandomString
{
<#
.SYNOPSIS
 Creates a new random string.
.DESCRIPTION
 This function creates a random string of 8 characters consisting of lowercase letters and numbers only. This randomly generated string can be used as name prefix,
 infix or suffixes for certain Azure resources such as storage accounts or public IP addresslables. This is because these resource names must be globally unique in DNS.
.EXAMPLE
 New-ARMDeployRandomString
 d0454deb
.INPUTS
 None
.OUTPUTS
 [string]$randomString
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Random, String
.LINK
 1: https://www.powershellgallery.com/packages/ARMDeploy
#>

    [OutputType([string])]
    [CmdletBinding()]
    param
    (
        [string]$randomString
    ) # end param
    $randomString = (New-Guid).Guid.Replace("-","").Substring(0,8)
    return $randomString
} # end function
function New-ARMDeployAssociateSubnetToNsg
{
<#
.SYNOPSIS
 Associates a subnet to an NSG.
.DESCRIPTION
 This function creates will associate a subnet to an NSG given the resource group name, VNET name, NSG name, subnet name and subnet range.
.EXAMPLE
 New-ARMDeployAssociateSubnetToNSG -resGroupName <resource group name> -vnetName <VNET name> -nsgName <NSG name> -subnetName <subnet name> -subnetRange <subnet range>
.PARAMETER resGroupName
 The resource group in which the virtual netwowrk, subnet and NSG is located.
.PARAMETER vnetName
 The Virtual Network containing the subnet that will be associated with the specified NSG.
.PARAMETER nsgName
 The NSG that will be associated with the subnet.
.PARAMETER subnetName
 The subnet that will be associated with the NSG
.PARAMETER subnetRange
 The subnet range of the subnet that will be associated to the NSG.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: NSG, Network Security Group, Subnet
.LINK
 1: https://www.powershellgallery.com/packages/ARMDeploy
#>

    [CmdletBinding()]
    param
    (
        [string]$resGroupName,
        [string]$vnetName,
        [string]$nsgName,
        [string]$subnetName,
        [string]$subnetRange
    ) # end parm

    $vnetResource = Get-AzVirtualNetwork -ResourceGroupName $resGroupName -Name $vnetName
    $nsgResource = Get-AzNetworkSecurityGroup -ResourceGroupName $resGroupName -Name $nsgName
    Set-AzVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork $vnetResource -AddressPrefix $subnetRange -NetworkSecurityGroup $nsgResource -Verbose
    $vnetResource | Set-AzVirtualNetwork -Verbose
} # end function
Function New-ARMDeployRandomPassword
{
 <#
.SYNOPSIS
Generates a random string of 12 characters based on specified criteria such as which character sets are required.
 
.DESCRIPTION
This function, New-ARMDeployRandomPassword.ps1, generates a fixed length string of 12 characters, consisting of a set of character types that you specify, such as uppercase, lowercase,
numbers and special characters. It is convenient to generate random strings multiple times from the same script, but with different character set combinations.
Some scenarios for which this function can be used includes; For passwords. In Azure, a minimum password length of 12 characters is required,
also Azure storage account names only accept lowercase and numeric characters, and Azure Site-To-Site VPN shared keys do not accept special characters.
 
.EXAMPLE
New-ARMDeployRandomPassword -IncludeUpper -IncludeLower -IncludeNumbers
In this example, we use 3 out of the available 4 charater set options. Any 3 of the 4 combination of the for character set switch parameters can be included.
 
.PARAMETER -IncludeUpper
Include upper case letters. This parameter is an optional switch
 
.PARAMETER -IncludeLower
Include lower case letters. This parameter is an optional switch
 
.PARAMETER -IncludeNumbers
Include numeric characters. This parameter is an optional switch
 
.PARAMETER -IncludeSpecial
Include special characters. This parameter is an optional switch
 
.INPUTS
[int]
[boolean]
 
.OUTPUTS
[string]
 
.NOTES
NAME: New-ARMDeployRandomPassword
 
REQUIREMENTS:
-Version 5.1
 
AUTHOR: Preston K. Parsard
 
ATTRIBUTION:
NA
 
LASTEDIT: 03 OCT 2020
 
KEYWORDS: Random, String, Passwords, Complexity
 
LICENSE:
The MIT License (MIT)
Copyright (c) 2020 Preston K. Parsard
 
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
DISCLAIMER:
THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. We grant You a nonexclusive,
royalty-free right to use and modify the Sample Code and to reproduce and distribute the Sample Code, provided that You agree: (i) to not use Our name,
logo, or trademarks to market Your software product in which the Sample Code is embedded;
(ii) to include a valid copyright notice on Your software product in which the Sample Code is embedded; and (iii) to indemnify, hold harmless,
and defend Us and Our suppliers from and against any claims or lawsuits, including attorneys’ fees,
that arise or result from the use or distribution of the Sample Code.
 
.LINK
https://technet.microsoft.com/en-us/ms376608.aspx
#>


[CmdletBinding(SupportsShouldProcess=$true,
    PositionalBinding=$false,
    HelpUri = 'https://gallery.technet.microsoft.com/scriptcenter',
    ConfirmImpact='Medium')]
 [OutputType([String])]
 Param
 (
  # Uppercase characters
  [switch] $IncludeUpper,

  # Lowercase characters
  [switch] $IncludeLower,

  # Numeric characters
  [switch] $IncludeNumbers,

  # Special characters
  [switch] $IncludeSpecial
 )

 # Lenth of random string
 [int]$StringLength = 12
 # Initialize array that will contain the custom combination of upper, lower, numeric and special complexity rules characters
 [string]$CharArray = @()
 # Initialize array of the default complexity rule set (uppercase, lowercase, numerical)
 [array]$RuleSets = @()
 # Initialize constructed string consisting of up to 12 characters, with characters from each of the 4 complexity rules
 [array]$StringArray = @()
 # The default number of samples taken from each of 3 complexity rules (Upper, Lower and Numeric) to construct the generated password string. SCR = String Complexity Rule.
 [int]$SampleCount = 0
 # Represents the combination of options selected: i.e. U = uppercase, L = lowercase, N = numeric and S = special. If all 4 options are selected, then the value of $Switches will be ULNS.
 [string]$Switches = $null

 # Alphabetic uppercase complexity rule
 $SCR1AlphaUpper = ([char[]]([char]65..[char]90))
 # Alphabetic lowercase complexity rule
 $SCR2AlphaLower = ([char[]]([char]97..[char]122))
 # Numeric complexity rule
 $SCR3Numeric = ([char[]]([char]48..[char]57))
 # Special characters complexity rule
 $SCR4Special = ([char[]]([char]33..[char]47)) + ([char[]]([char]58..[char]64)) + ([char[]]([char]92..[char]95)) + ([char[]]([char]123..[char]126))

 # Combine all complexity rules arrays into one consolidated array for all possible character values

 # Detect which switch parameters were used
 If ($IncludeUpper) { $Switches = "U" }
 If ($IncludeLower) { $Switches += "L" }
 If ($IncludeNumbers) { $Switches += "N" }
 If ($IncludeSpecial) { $Switches += "S" }

 If ($Switches.Length -gt 0)
 {
  # Calculate # of characters to sample per rule set
  [int]$SampleCount = $StringLength/($Switches.Length)
   Switch ($Switches)
   {
    # Alphabetic uppercase complexity rule
    {$_ -match 'U'}
    {
     Get-Random -InputObject $SCR1AlphaUpper -Count $SampleCount | ForEach-Object { $StringArrayU += $_ }
     $StringArray += $StringArrayU
    } #end -match

    # Alphabetic lowercase complexity rule
    {$_ -match 'L'}
    {
     Get-Random -InputObject $SCR2AlphaLower -Count $SampleCount | ForEach-Object { $StringArrayL += $_ }
    $StringArray += $StringArrayL
    } #end -match

    # Numeric complexity rule
    {$_ -match 'N'}
    {
     Get-Random -InputObject $SCR3Numeric -Count $SampleCount | ForEach-Object { $StringArrayN += $_ }
     $StringArray +=  $StringArrayN
    } #end -match

    # Special characters complexity rule
    {$_ -match 'S'}
    {
     Get-Random -InputObject $SCR4Special -Count $SampleCount | ForEach-Object { $StringArrayS += $_ }
     $StringArray +=  $StringArrayS
    } #end -match
   } #end Switch
 } #end If
 Else
 {
  # No options were specified
  [int]$SampleCount = 4
  [string]$CharArray = $SCR1AlphaUpper + $SCR2AlphaLower + $SCR3Numeric
  # Construct an array of 3 complexity rule sets
  [array]$RuleSets = ($SCR1AlphaUpper, $SCR2AlphaLower, $SCR3Numeric)
  # Generate a specified set of characters from each of the 4 complexity rule sets
  ForEach ($RuleSet in $RuleSets)
  {
   Get-Random -InputObject $RuleSet -Count $SampleCount | ForEach-Object { $StringArray += $_ }
  } #end ForEach
 } #end Else

 [string]$RandomPasswordWithSpaces = $StringArray
 $RandomPassword = $RandomPasswordWithSpaces.Replace(" ","")
 # Write-Host "`$Switches selected: $Switches"
 # Write-Host "Randomly generated 12 character string: " $RandomString
 return $RandomPassword

} #end Function

function Install-ARMDeployAzStorageModuleSpecificVersion
{
    [CmdletBinding()]
    param
    (
        [string]$excludeModule = "Az.Storage",
        [string]$requiredVersion = "2.1.0",
        [string]$Repository = "PSGallery"
    ) # end param

    # Exclusive installation of version Az.Storage 2.1.0
    # Find and install all Az modules except Az.Storage
    Write-Output "Finding required Az modules to install. Please wait..."
    $targetParentAzModule = "Az"
    $azModules = (Find-Module -Name $targetParentAzModule -IncludeDependencies -ErrorAction SilentlyContinue).Name
    $checkForVersion210 = (Get-InstalledModule -Name $excludeModule -RequiredVersion $requiredVersion -ErrorAction SilentlyContinue).Version
    foreach ($azModule in $azModules)
    {
        If ($azModule -ne $excludeModule)
        {
            Install-Module -Name $azModule -Repository $Repository -Verbose
        } # end if
        elseif ($checkForVersion210 -ne $requiredVersion)
        {
            # If required version is not present then install it
            Write-Output "Module $excludeModule and version $requiredVersion is not installed. Installing now..."
            Install-Module -Name $excludeModule -Repository $Repository -RequiredVersion $requiredVersion -AllowClobber -Force -Verbose
        } # end else
        else
        {
            Write-Output "The required module $excludeModule and version $requriedVersion is already installed."
        } # end else
    } # end foreach
    Import-Module -Name $excludeModule -RequiredVersion $requiredVersion -Verbose
} # end function

Export-ModuleMember -Function *ARMDeploy* -Verbose