forked from jagilber/powershellScripts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
azure-rm-rdp-post-deployment.ps1
1506 lines (1281 loc) · 48.9 KB
/
azure-rm-rdp-post-deployment.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
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
<#
.SYNOPSIS
powershell script to connect to quickstart rds deployments after deploying template
.DESCRIPTION
https://gallery.technet.microsoft.com/Azure-Resource-Manager-4ea7e328
** REQUIRES AT LEAST WMF 5.0 AND AZURERM SDK **
script authenticates to azure rm
queries all resource groups for public ip name
gives list of resource groups
enumerates public ip of specified resource group
downloads certificate from RDWeb
adds cert to local machine trusted root store
tries to resolve subject name in dns
if not the same as public loadbalancer ip address it is added to hosts file
start with -verbose if you need to troubleshoot script
.NOTES
NOTE: to remove certs from all stores Get-ChildItem -Recurse -Path cert:\ -DnsName *<%subject%>* | Remove-Item
File Name : azure-rm-rdp-post-deployment.ps1
Version : 180721 fix issue where nsg attached to nic didnt have all necessary properties populated
History :
170908 updated commands to remove public ip
170809 checking vm for 3389 and 443 for nsg
170807 fix for $ipAddress.IPAddress
.EXAMPLE
.\azure-rm-rdp-post-deployment.ps1
query azure rm for all resource groups with for all public ips.
.EXAMPLE
.\azure-rm-rdp-post-deployment.ps1 -rdWebUrl https://contoso.eastus.cloudapp.azure.com/RDWeb
used to bypass Azure enumeration and to copy cert from url to local cert store
.PARAMETER addPublicIp
add public ip address and nsg to selected virtual machine
.PARAMETER enumerateSubscriptions
to query all subscriptions and not just current one
.PARAMETER noPrompt
to not prompt when adding cert to cert store or when modifying hosts file
.PARAMETER rdWebUrl
used to pass complete RDWeb url to script to bypass Azure enumeration. will add self-signed cert to cert store.
.PARAMETER resourceManagerName
optional parameter to specify Resource Group Name
.PARAMETER publicIpAddressName
optional parameter to override ip resource name public ip address
.PARAMETER update
optional parameter to check for updated script from github
#>
param(
[switch]$addPublicIp,
[string][ValidateSet('LocalMachine', 'CurrentUser')] $certLocation = "LocalMachine",
[switch]$enumerateSubscriptions,
[switch]$noprompt,
[switch]$noretry,
[int[]]$ports = @(3389),
[string]$publicIpAddressName = ".",
[string]$rdWebUrl = "",
[string]$resourceGroupName,
[switch]$update,
[string]$vmName
)
set-strictmode -version Latest
$ErrorActionPreference = "SilentlyContinue"
$WarningPreference = "SilentlyContinue"
$global:redisplay = $true
$global:selfSigned = $false
$global:san = $false
$global:wildcard = $false
$hostsTag = "added by azure script"
$hostsFile = "$($env:windir)\system32\drivers\etc\hosts"
$updateUrl = "https://aka.ms/azure-rm-rdp-post-deployment.ps1"
$profileContext = "$($env:TEMP)\ProfileContext.ctx"
$throttle = 10
# ----------------------------------------------------------------------------------------------------------------
function main()
{
$error.Clear()
$subList = @{}
$rg = $null
$subject = $null
$certInfo = $null
$startTime = get-date
write-host "starting script $($MyInvocation.ScriptName) to enumerate public ip addresses and RDWeb sites in Azure RM"
if ($update -and (get-update -updateUrl $updateUrl -destinationFile $MyInvocation.ScriptName))
{
return
}
# need to run as admin
if (($ret = runas-admin) -eq $false)
{
return
}
if ($rdWebUrl)
{
# go directly to url
write-host "connecting to rdWebUrl $($rdWebUrl)"
$certFile = [IO.Path]::GetFullPath("$($rdWebUrl -replace '\W','').cer")
$cert = get-cert -url $rdWebUrl -certFile $certFile
$subject = enum-certSubject -cert $cert
#$ipv4 = ([regex]::Matches($rdWebUrl, "((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])")).Captures
$ipv4 = [regex]::Matches($rdWebUrl, "((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])")
if($ipv4.Count -gt 1)
{
$subject = import-cert -cert $cert -certFile $certFile -subject $subject -wildcardname "gateway"
if ($subject)
{
add-hostsEntry -ipAddress $ipv4.Captures[0].Value -subject $subject
open-RdWebSite -site $rdWebUrl
return
}
}
}
# connect to azure
authenticate-azureRm
$subscriptions = @(get-subscriptions)
$global:redisplay = $true
if($addPublicIp -and $subscriptions.Count -gt 0)
{
add-publicIp
#return
}
while ($global:redisplay -and $subscriptions.Count -gt 0)
{
$global:redisplay = $false
foreach ($sub in $subscriptions)
{
$resourceList = New-Object Collections.ArrayList
if (!$sub)
{
continue
}
if($enumerateSubscriptions)
{
Set-AzureRmContext -SubscriptionId $sub
}
write-host "subscription id $($sub)"
$resourceList = enum-resourcegroup $sub
$count = 1
write-host "Displaying ONLY Azure RM resources with public IP addresses that are currently connectable." -ForegroundColor Cyan
Write-Host "Green indicates RDWeb site:" -ForegroundColor Green
foreach($resource in $resourceList)
{
if($resource.DisplayMessage)
{
write-host "$($count). $($resource.displayMessage)" -ForegroundColor $resource.displayMessageColor
$resource.Id = $count
$count++
}
}
if(!$resourceList -or $resourceList.Count -lt 1)
{
write-host "no ip addresses found.."
if((read-host "do you want to add a public ip address to an existing vm?[y|n]") -imatch "y")
{
add-publicIp
$global:redisplay = $true
#return
}
continue
}
elseif ($resourceList.Count -gt 1)
{
write-verbose "query time: $(((get-date) - $startTime).TotalSeconds)"
write-host "(advanced) if connection is not listed and vm is running, enter 'p' to add public ip address"
$idsEntry = Read-Host ("Enter number for site / ip address to connect to.")
}
elseif ($resourceList.Count -eq 1)
{
$id = 1
}
$ids = check-response -response $idsEntry
foreach ($id in $ids)
{
if(!([Convert]::ToInt32($id)))
{
write-host "invalid entry $($id)..."
continue
}
[int]$id = [Convert]::ToInt32($id)
if ($id -gt $resourceList.Count -or $id -lt 1)
{
write-host "entry out of range $($id)..."
continue
}
$resource = $resourceList | where Id -eq $id
write-host $resource.ResourceGroup
write-verbose "enum-resourcegroup returning:$($resource | fl | out-string)"
$ip = $resource.publicIp
#if ($ip.IpAddress)
if ($resource.certInfo)
{
write-host "public ip address: $($ip.IpAddress)"
$gatewayUrl = "https://$($ip.IpAddress)/RDWeb"
$certFile = [IO.Path]::GetFullPath("$($gatewayUrl -replace '\W','').cer")
$cert = get-cert -url $gatewayUrl -certFile $certFile
$subject = enum-certSubject -cert $resource.certInfo
$subject = import-cert -cert $cert -certFile $certFile -subject $subject -wildcardname $resource.ResourceGroup
add-hostsEntry -ipAddress $ip.IpAddress -subject $subject
open-RdWebSite -site "https://$($subject)/RDWeb"
}
else
{
start-mstsc -ip $ip
}
}
} # end foreach
if(!$resourceList)
{
write-warning "no machines are available to connect to. exiting"
break
}
} # end while
if(test-path $profileContext)
{
Remove-Item -Path $profileContext -Force
}
write-host "finished"
}
# ----------------------------------------------------------------------------------------------------------------
function add-hostsEntry($ipAddress, $subject)
{
# see if it needs to be added to hosts file
$addIp = $false
try
{
try
{
$dnsresolve = @(Resolve-DnsName -Name $subject -ErrorAction SilentlyContinue)
$dnsIP0 = ""
if($error)
{
$addIp = $true
$error.Clear()
}
elseif(!$dnsresolve -or $dnsresolve.Count -lt 1)
{
$addIp = $true
}
elseif(!$dnsresolve.IpAddress -or !$dnsresolve.IpAddress.Contains($ipAddress))
{
$addIp = $true
}
}
catch {}
if ($addIp)
{
if($dnsresolve -and $dnsresolve.IpAddress)
{
$dnsIP0 = @($dnsresolve.IpAddress)[0]
}
write-host "$($ipAddress) not same as $($dnsIP0), checking hosts file"
if (!$noPrompt -and (read-host "Is it ok to modify hosts file and add $($ipAddress)?[y|n]") -ine 'y')
{
return $false
}
# check hosts file
[string]$hostFileInfo = [IO.File]::ReadAllText($hostsFile)
if ($hostFileInfo -imatch $subject)
{
# remove from hosts file
[IO.StreamReader]$rStream = [IO.File]::OpenText($hostsFile)
$newhostFileInfo = New-Object Text.StringBuilder
while (($line = $rStream.Readline()) -ne $null)
{
if (![regex]::IsMatch($line, "(\S+:\S+|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\s+?$($subject)"))
{
[void]$newhostFileInfo.AppendLine($line)
}
else
{
write-host "removing $($line) from $($hostsFile)"
}
}
$rStream.Close()
[IO.File]::WriteAllText($hostsFile, $newhostFileInfo.ToString())
}
# add to hosts file
$newEntry = "$($ipAddress)`t$($subject)`t# $($hostsTag) $([IO.Path]::GetFileName($MyInvocation.ScriptName)) $([DateTime]::Now.ToShortDateString())`r`n"
write-host "adding new entry:$($newEntry)"
[IO.File]::AppendAllText($hostsFile, $newEntry)
type $hostsFile
}
else
{
write-host "dns resolution for $($subject) same as ip:$($ipAddress)"
}
}
catch
{
write-host "add-hostname:exception: $($error | out-string)"
}
}
# ----------------------------------------------------------------------------------------------------------------
function add-publicIp()
{
try
{
# verify
Write-host "This process will add a dynamic public ip address to an existing vm that only has a private ip address" -ForegroundColor Yellow
Write-host "It will use an existing NSG or will create a new one. The only port open will be 3389 for RDP" -ForegroundColor Yellow
Write-host "WARNING: this is exposing the selected virtual machines TCP port 3389 externally on internet." -ForegroundColor Yellow
Write-host "If this is NOT correct, press ctrl-c to exit script." -ForegroundColor Yellow
if((Read-Host "Confirm you want to continue:[y|n]") -inotmatch "y")
{
exit
}
$nsgnames = $Null
$ret = $null
$resourceGroups = Get-AzureRmResourceGroup
$vms = new-object Collections.ArrayList
if(!$resourceGroupName -and $resourceGroups -or !($resourceGroups.ResourceGroupName -imatch $resourceGroupName))
{
write-host "resource groups:" -ForegroundColor Cyan
write-host ($resourceGroups.ResourceGroupName | out-string)
$resourceGroupName = read-host "Enter name of resource group to enumerate"
}
if(!$resourceGroupName)
{
exit
}
foreach($vm in (Get-AzureRmVM -ResourceGroupName $resourceGroupName))
{
[void]$vms.Add($vm)
}
if(!$vmName)
{
write-host "virtual machines:" -ForegroundColor Cyan
write-host ($vms.Name | out-string)
$modifiedVmName = read-host "Enter name of vm to add public ip address"
}
else
{
$modifiedVmName = $vmName
}
if(!$modifiedVmName)
{
exit
}
$modifiedVm = get-azurermvm -ResourceGroupName $resourceGroupName -Name $modifiedVmName
$vmNicName = [IO.Path]::GetFileName(@($modifiedVm.NetworkProfile.NetworkInterfaces.Id)[0])
$vmNic = Get-AzureRmNetworkInterface -ResourceGroupName $resourceGroupName -Name $vmNicName
$vmSubnetName = [IO.Path]::GetFileName(@($vmNic.IpConfigurations)[0].subnet.id)
$vmPrivateIpAddress = $vmNic.IpConfigurations.privateipaddress
$vmPublicIpAddress = $vmNic.IpConfigurations.publicipaddress
#$publicIp = Get-AzureRmPublicIpAddress -ResourceGroupName $resourceGroupName -Name $vmNicName -ErrorAction SilentlyContinue
$vmStatus = (get-azurermvm -ResourceGroupName $resourceGroupName -Name $modifiedVmName -Status).Statuses
if(!($vmStatus.Code -imatch "running"))
{
write-host "error: vm is NOT running! start vm and restart script. exiting" -ForegroundColor Red
exit
}
write-host "vm name: $($modifiedVm.Name)"
write-host "`tprivate ip address: $($vmPrivateIpAddress)"
write-host "`tpublic ip address: $($vmPublicIpAddress)"
write-host "`tsubnet: $($vmSubnetName)"
write-host "`tstatus: running"
if($vmPublicIpAddress)
{
write-host "vm $($modifiedVm.Name) already has public ip address $($vmPublicIpAddress). exiting" -ForegroundColor Red
exit
}
$rgLocation = (get-azurermresourcegroup -Name $resourceGroupName).Location
write-host "using location: $($rgLocation)"
$newNsgName = $nsgName = "$($modifiedVmName)-nsg"
$nsg = $vmNic.NetworkSecurityGroup
if($nsg)
{
# may not be populated but needs to be
if(!$nsg.ResourceGroupName) {$nsg.ResourceGroupName = $resourceGroupName}
if(!$nsg.Location) {$nsg.Location = $rgLocation}
if(!$nsg.Name) {$nsg.Name = $newNsgName}
}
$nsgs = @(Get-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroupName)
if(!$nsg)
{
if($nsgs)
{
write-host "all nsg's in resource group:" -ForegroundColor Cyan
write-host ($nsgs.Name | out-string)
write-host "nsg's in resource group on same subnet:" -ForegroundColor Cyan
try
{
$nsgNames = @([Linq.Enumerable]::Where($nsgs, [Func[object,bool]]{ param($x) $x.Subnets.Id -imatch $vmSubnetName }).Name)
}
catch
{
$error.Clear()
}
write-host ($nsgNames | out-string)
write-host "nsg's in resource group with TCP 3389 Allow Rule:" -ForegroundColor Cyan
try
{
$nsgNames = @([Linq.Enumerable]::Where($nsgs, [Func[object,bool]]{ param($x) $x.SecurityRules.DestinationPortRange -imatch 3389 }).Name)
}
catch
{
$error.Clear()
}
write-host ($nsgNames | out-string)
}
$nsgName = read-host "enter name of existing nsg to use, new nsg name to create new nsg, or press {enter} to use new name '$($newNsgName)'"
if(!$nsgName)
{
$nsgName = $newNsgName
}
if($nsgName -and !($nsgNames -imatch $nsgName))
{
write-host "creating new nsg $($nsgName). please wait..." -ForegroundColor Yellow
write-host "`t New-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroupName -Name $nsgName -Location $rgLocation" -ForegroundColor Gray
$nsg = New-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroupName -Name $nsgName -Location $rgLocation
}
elseif($nsgName -and ($nsgNames -imatch $nsgName))
{
# on same subnet
$nsg = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroupName -Name $nsgName
}
else
{
exit
}
}
if(!$nsg)
{
exit
}
foreach($port in $ports)
{
#if(test-port -ipAddress $vmPrivateIpAddress -port $port)
$foundRule = $false
if($true)
{
write-host "checking for security rule for $($port)"
foreach($rule in $nsg.SecurityRules)
{
if($rule.DestinationPortRange -imatch $port -and $rule.DestinationAddressPrefix -eq "*")
{
$foundRule = $true
}
}
if($foundRule)
{
write-host "using existing security rule for $($port)..." -ForegroundColor Green
}
else
{
write-host "creating security rule for $($port)"
# check for open priority
$priority = $Null
if($nsg.SecurityRules.Count -gt 0)
{
$priorities = $nsg.SecurityRules.Priority
foreach($priority in 100..4096)
{
if ($priorities -ieq $priority)
{
continue
}
else
{
break
}
}
}
else
{
$priority = 100
}
write-host "`t Add-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg `
-Name AllowRDP `
-Direction Inbound `
-Priority $priority `
-Access Allow `
-SourceAddressPrefix '*' `
-SourcePortRange '*' `
-DestinationAddressPrefix '*' `
-DestinationPortRange $($port) `
-Protocol TCP `
-ErrorAction Stop" -foregroundColor Gray
$ret = Add-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg `
-Name "Allow$($port)" `
-Direction Inbound `
-Priority $priority `
-Access Allow `
-SourceAddressPrefix '*' `
-SourcePortRange '*' `
-DestinationAddressPrefix '*' `
-DestinationPortRange $($port) `
-Protocol TCP `
-ErrorAction Stop
#$vmPrivateIPAddress `
}
write-host "saving security rule for TCP RDP $($port). please wait..." -ForegroundColor Yellow
$ret = Set-AzureRmNetworkSecurityGroup -NetworkSecurityGroup $nsg -ErrorAction Stop
$vmNic.NetworkSecurityGroup = $nsg
}
else
{
write-host "warning:port $($port) not responding. skipping"
}
} # end foreach
write-host "creating public ip. please wait..." -ForegroundColor Yellow
write-host "`t New-AzureRmPublicIpAddress -Name $($modifiedVmName)-pubIp `
-ResourceGroupName $resourceGroupName `
-AllocationMethod Dynamic `
-Location $rgLocation" -ForegroundColor Gray
$vmPublicIP = New-AzureRmPublicIpAddress -Name "$($modifiedVmName)-pubIp" `
-ResourceGroupName $resourceGroupName `
-AllocationMethod Dynamic `
-Location $rgLocation
write-host "setting vm $($modifiedVmName) network interface to use public ip. please wait..." -ForegroundColor Yellow
#$ret = Add-AzureRmNetworkInterfaceIpConfig -Name $vmPublicIP.Name -NetworkInterface $vmNic
#$ret = Set-AzureRmNetworkInterfaceIpConfig -name $vmPublicIP.Name -NetworkInterface $vmNic -PublicIpAddress $vmPublicIP
$vmNic.IpConfigurations[0].PublicIpAddress = $vmPublicIp
$ret = Set-AzureRmNetworkInterface -NetworkInterface $vmNic
write-host "`t (get-AzureRmPublicIpAddress -ResourceGroupName $resourceGroupName -Name $vmPublicIP.Name).IpAddress" -ForegroundColor Gray
$vmPublicIpAddress = (get-AzureRmPublicIpAddress -ResourceGroupName $resourceGroupName -Name $vmPublicIP.Name).IpAddress
if($vmPublicIpAddress)
{
write-host "new public ip address: $($vmPublicIpAddress)" -ForegroundColor Green
}
else
{
write-host "unable to acquire public ip address. exiting" -ForegroundColor Red
exit
}
write-host "successfully added public ip address $($vmPublicIPAddress) to vm $($modifiedVmName)" -ForegroundColor Green
write-host "To remove public ip address and nsg, use the following commands:" -ForegroundColor Magenta
write-host "`t `$nic = (Get-AzureRmNetworkInterface -ResourceGroupName $($resourceGroupName) -Name $($vmNicName))" -ForegroundColor Cyan
write-host "`t `$nic.IpConfigurations.publicipaddress = `$null" -ForegroundColor Cyan
write-host "`t `$nic.NetworkSecurityGroup = `$null" -ForegroundColor Cyan
write-host "`t Set-AzureRmNetworkInterface -NetworkInterface `$nic" -ForegroundColor Cyan
write-host "`t Remove-AzureRmPublicIpAddress -Name $($modifiedVmName)-pubIp -ResourceGroupName $($resourceGroupName) -Force" -ForegroundColor Cyan
write-host "`t Remove-AzureRmNetworkSecurityGroup -Name $($nsgName) -ResourceGroupName $($resourceGroupName) -Force" -ForegroundColor Cyan
write-host ""
}
catch
{
write-host "add-publicIp:error: $($error | out-string)"
exit
}
}
# ----------------------------------------------------------------------------------------------------------------
function authenticate-azureRm()
{
# make sure at least wmf 5.0 installed
if ($PSVersionTable.PSVersion -lt [version]"5.0.0.0")
{
write-host "update version of powershell to at least wmf 5.0. exiting..." -ForegroundColor Yellow
start-process "https://www.bing.com/search?q=download+windows+management+framework+5.0"
# start-process "https://www.microsoft.com/en-us/download/details.aspx?id=50395"
exit
}
# verify NuGet package
$nuget = get-packageprovider nuget -Force
if (-not $nuget -or ($nuget.Version -lt [version]::New("2.8.5.22")))
{
write-host "installing nuget package..."
install-packageprovider -name NuGet -minimumversion ([version]::New("2.8.5.201")) -force
}
$allModules = (get-module azure* -ListAvailable).Name
# install AzureRM module
if ($allModules -inotcontains "AzureRM")
{
# each has different azurerm module requirements
# installing azurerm slowest but complete method
# if wanting to do minimum install, run the following script against script being deployed
# https://raw.githubusercontent.com/jagilber/powershellScripts/master/script-azurerm-module-enumerator.ps1
# this will parse scripts in given directory and output which azure modules are needed to populate the below
# at least need profile, resources, insights, logicapp for this script
if ($allModules -inotcontains "AzureRM.profile")
{
write-host "installing AzureRm.profile powershell module..."
install-module AzureRM.profile -force
}
if ($allModules -inotcontains "AzureRM.resources")
{
write-host "installing AzureRm.resources powershell module..."
install-module AzureRM.resources -force
}
if ($allModules -inotcontains "AzureRM.compute")
{
write-host "installing AzureRm.compute powershell module..."
install-module AzureRM.compute -force
}
if ($allModules -inotcontains "AzureRM.network")
{
write-host "installing AzureRm.network powershell module..."
install-module AzureRM.network -force
}
Import-Module azurerm.profile
Import-Module azurerm.resources
Import-Module azurerm.compute
Import-Module azurerm.network
#write-host "installing AzureRm powershell module..."
#install-module AzureRM -force
}
else
{
Import-Module azurerm
}
# authenticate
try
{
$rg = @(Get-AzureRmTenant)
if($rg)
{
write-host "auth passed $($rg.Count)"
}
else
{
write-host "auth error $($error)" -ForegroundColor Yellow
throw [Exception]
}
}
catch
{
if(!(connect-azurermaccount))
{
log-info "exception authenticating. exiting $($error | out-string)" -ForegroundColor Yellow
exit 1
}
}
Save-AzureRmContext -Path $profileContext -Force
}
# ----------------------------------------------------------------------------------------------------------------
function check-jobs()
{
$resultList = new-object Collections.ArrayList
$ret = $null
$jobInfos = $null
foreach($job in get-job)
{
if($job.State -ine "Running")
{
$jobInfos = (Receive-Job -Job $job)
foreach($jobInfo in $jobInfos)
{
if($jobInfo -and ($jobInfo.GetType().Name -eq "HashTable"))
{
[void]$resultList.Add($jobInfo)
}
elseif($jobInfo)
{
Write-Warning $jobInfo | out-string
}
else
{
Write-verbose "job returned empty result"
}
}
$ret = Remove-Job -Job $job -Force
}
}
return $resultList
}
# ----------------------------------------------------------------------------------------------------------------
function check-response($response)
{
[string[]] $ids = @()
#check ids for comma and range
if ($response.ToLower().Contains("c"))
{
# redisplay list to choose again
$response = $response.ToLower().Replace("c", "")
$global:redisplay = $true
}
elseif ($response.ToLower().Contains("p"))
{
# go through public ip setup
$response = $response.ToLower().Replace("p", "")
add-publicIp
$global:redisplay = $true
return
}
else
{
$global:redisplay = $false
}
if ($response.Contains(","))
{
$ids = @($response.Split(","))
}
else
{
$ids = @($response)
}
return $ids
}
# ----------------------------------------------------------------------------------------------------------------
function enum-certSubject($cert)
{
# get certificate from RDWeb site
if (!$cert)
{
write-host "no cert!"
return $false
}
$subject = $cert.Subject.Replace("CN=", "")
if ($subject)
{
return $subject
}
return $false
}
# ----------------------------------------------------------------------------------------------------------------
function enum-resourcegroup([string] $subid)
{
write-verbose "enum-resourcegroup"
$resourceGroup = $null
$id = 0
$displayMessage = ""
$pubIps = @()
$vms = @()
$resourceList = New-Object Collections.ArrayList
$resultList = New-Object Collections.ArrayList
$ret = New-Object Collections.ArrayList
$response = $null
# cleanup
if(get-job)
{
write-host "removing $(@(get-job).Count) old jobs..."
get-job | remove-job -Force
}
try
{
if(!$noprompt -and !$resourceGroupName)
{
write-host "resource group names:" -ForegroundColor Cyan
$resourceGroupNames = [collections.ArrayList]@((Get-AzureRmResourceGroup).ResourceGroupName)
$count = 1
foreach($name in $resourceGroupNames)
{
write-host "$($count). $($name)"
$count++
}
Write-Host
$response = read-host "enter number for resource group to enumerate or press {enter} to enumerate all:"
$resourceGroupName = check-response -response $response
}
# find resource group
if (!$resourceGroupName)
{
#$Null = Set-AzureRmContext -SubscriptionId $subid
$resourceGroups = Get-AzureRmResourceGroup -WarningAction SilentlyContinue
$count = 1
}
else
{
try
{
if([Convert]::ToInt32($resourceGroupName))
{
$resourceGroups = @(Get-AzureRmResourceGroup -Name ($resourceGroupNames[$resourceGroupName - 1]) -WarningAction SilentlyContinue)
}
}
catch
{
$resourceGroups = @(Get-AzureRmResourceGroup -Name $resourceGroupName -WarningAction SilentlyContinue)
}
}
foreach($resourceGroup in $resourceGroups.ResourceGroupName)
{
$pubIps = @(Get-AzureRmPublicIpAddress -ResourceGroupName $resourceGroup | ? IpAddress -ine "Not Assigned")
write-host "checking $($pubIps.count) ip addresses in $($resourceGroup)."
foreach($ip in $pubIps)
{
if($resourceGroup -imatch $ip.ResourceGroupName)
{
$resource = @{}
$resource.Id = 0
$resource.publicIp = $ip
$resource.subId = $subid
$resource.displayMessage = "`r`n`tResource Group: $($resourceGroup)`r`n`tIP name: $($ip.Name)`r`n`tIP address: $($ip.IpAddress)"
$resource.resourceGroup = $resourceGroup
$resource.rdWebUrl = ""
$resource.certInfo = $null
$resource.displayMessageColor = "White"
$resource.profileContext = $profileContext
$resource.invocation = $MyInvocation
[void]$resourceList.Add($resource)
}
}
}
$jobs = New-Object Collections.ArrayList
foreach($resource in $resourceList)
{
while((get-job) -and (@(get-job | where-object State -eq "Running").Count -gt $throttle))
{
Write-Verbose "throttled"
$ret = check-jobs
if($ret)
{
if($ret.gettype().Name -eq "Object[]")
{
$resultList.AddRange($ret)
}
else
{
$resultList.Add($ret)
}
}
Start-Sleep -Seconds 1
}
$job = start-job -ScriptBlock `
{
param($resource)
$ctx = $null
$displayMessage = $null
$t = $null
#background job for bug https://github.com/Azure/azure-powershell/issues/7110
Disable-AzureRmContextAutosave -scope Process -ErrorAction SilentlyContinue | Out-Null
$ctx = Import-AzureRmContext -Path $resource.profileContext
# bug to be fixed 8/2017
# From <https://github.com/Azure/azure-powershell/issues/3954>
[void]$ctx.Context.TokenCache.Deserialize($ctx.Context.TokenCache.CacheData)
. $($resource.invocation.scriptname)
$displayMessage = $resource.displayMessage
$t = New-Object Net.Sockets.TcpClient
try
{
$t.Connect($resource.publicIp.IpAddress,3389)
$resource.displayMessage = " VM: mstsc.exe /v $($resource.publicIp.IpAddress) /admin$($displayMessage)"
# write results to pipe
$resource
}
catch {}
[void]$t.Dispose()
$t = New-Object Net.Sockets.TcpClient
try
{
$t.Connect($resource.publicIp.IpAddress,443)
$resource.rdWebUrl = "https://$($resource.publicIp.IpAddress)/RDWeb"
$resource.certInfo = (get-cert -url $resource.rdWebUrl)
if ($resource.certInfo)
{
$resource.displayMessage = " RDWEB: $($resource.rdWebUrl)$($displayMessage)`r`n`tCert Subject: $(enum-certSubject -cert $resource.certInfo)"
$resource.displayMessageColor = "Green"
# write results to pipe
$resource
}
}
catch {}
[void]$t.Dispose()
} -ArgumentList $resource
[void]$jobs.Add($job)
}
$jobsCount = $jobs.Count
$activity = "checking connectivity to $($jobsCount) public ips. please wait.."
while(get-job)