-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathARMRunSchedule.psm1
1471 lines (1360 loc) · 55.7 KB
/
ARMRunSchedule.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
#Requires -Modules AzureRM.Compute, AzureRM.Resources
#Requires -Version 5
<#
.SYNOPSIS
This PowerShell module contains functions related to manipuliating the RunSchedule tag on Azure RM resources.
.DESCRIPTION
This PowerShell module contains functions related to manipuliating the RunSchedule tag on Azure RM resources.
.NOTES
Author: Jeff Reed
Name: RunSchedule.psm1
Created: 2018-08-20
Email: [email protected]
#>
# Start Module Functions
function Connect-AzureRM {
<#
.SYNOPSIS
Signs into AzureRM if the user is not already signed in.
.DESCRIPTION
Signs into AzureRM if the user is not already signed in.
.EXAMPLE
Login-AzureRM
#>
[CmdletBinding()]
param()
# login into your azure account
try
{
$AzureRMContext = Get-AzureRMContext
}
catch
{
try {
$a = Add-AzureRMAccount
}
catch {
$command = $_.InvocationInfo.MyCommand.Name
$ex = $_.Exception
$m =("{0} failed: {1}" -f $command, $ex.Message)
Throw $m
}
}
if ($AzureRMContext.Account -eq $Null) {
$a = Add-AzureRMAccount
}
} # End function Login-AzureRM
function Select-Subscription {
<#
.SYNOPSIS
Sets the Azure RM Context to the Azure subscription specified.
.DESCRIPTION
Sets the Azure RM Context to the Azure subscription specified. If the SubscriptionId is
not specified, a gridview of available Azure subscriptions will be presented in order
for the user to select a subscription.
.PARAMETER SubscriptionId
An Azure subscription ID.
.EXAMPLE
Select-Subscription
.EXAMPLE
Select-Subscription -SubscriptionId "f1bb2e3d-fbec-4dd8-9e46-fb998a30246f"
#>
[CmdletBinding()]
Param
(
[Parameter(
Position=0,
ParameterSetName='CmdLine',
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="An Azure subscription ID."
)]
[string] $SubscriptionId
)
# Check if SubscriptionId parameter was set
if (-not ($PSBoundParameters.ContainsKey("SubscriptionId") ) ) {
# Parameter wasn't set. Get the subscriptions enabled for this user
# In AzureRM.Profile 2.8.0 the property is SubscriptionId. In 3.0.0 it is changed to Id
$s = Get-AzureRmSubscription | Where-Object State -eq "Enabled" | Out-GridView -Title "Select an Azure Subscription" -OutputMode Single
if ($s.Id -eq $Null) {
$SubscriptionId = $s.SubscriptionId
}
else {
$SubscriptionId = $s.Id
}
}
try {
# Change the subscription context
$AzureRMContext = Set-AzureRmContext -SubscriptionId $SubscriptionId
}
catch {
$command = $_.InvocationInfo.MyCommand.Name
$ex = $_.Exception
$m =("{0} failed: {1}" -f $command, $ex.Message)
Throw $m
}
} # End function Select-Subscription
function Save-ARMContext {
<#
.SYNOPSIS
Saves the Azure RM Context to a file in the interactive user's profile.
.DESCRIPTION
Saves the Azure RM Context to a file in the interactive user's profile
.PARAMETER SubscriptionId
An Azure subscription ID.
.EXAMPLE
Save-ARMContext
.EXAMPLE
Save-ARMContext -SubscriptionId "f1bb2e3d-fbec-4dd8-9e46-fb998a30246f"
#>
[CmdletBinding()]
Param
(
[Parameter(
Position=0,
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The Azure subscription ID."
)]
[string] $SubscriptionId
)
# Make sure we are signed into Azure
Connect-AzureRM
if ($PSBoundParameters.ContainsKey("SubscriptionId") ) {
Select-Subscription -SubscriptionId $SubscriptionId
}
else {
Select-Subscription
}
# Save the interactive Azure profile to a file in the user's home directory
# This is necessary in order to start background jobs using this users creds
Save-AzureRmContext -Path $script:AzureProfile -Force | Out-Null
}
function Find-Resources {
<#
.SYNOPSIS
Returns an array of resources based on JSON input file
.DESCRIPTION
Returns an array of resources based on JSON input file
.PARAMETER ResourceGroupName
The name of the resource group containing the resource.
.PARAMETER Name
The name of the resource.
.PARAMETER Tag
If specified the tag will be updated on the resource.
If specified but a null string, the tag will be removed.
If not specified no action is taken on the tag.
.PARAMETER FilterPath
An optional JSON file that specifies a filter of resources, so that all resources in a subscription are not examined.
.PARAMETER Action
The action to the perfom the resources, either Get, Set, or Remove.
.EXAMPLE
Find-Resources -FilterPath "C:\Temp\resource-Filter.json"
.OUTPUTS
An array of AzureRM resource objects that match the input filter
#>
[CmdletBinding(
DefaultParameterSetName="JSONFile"
)]
Param (
[Parameter(
Position=0,
ParameterSetName='CmdLine',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The name of the resource group containing the resource."
)]
[string] $ResourceGroupName,
[Parameter(
Position=1,
ParameterSetName='CmdLine',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The name of the resource."
)]
[string] $Name,
[Parameter(
Position=0,
ParameterSetName='JSONFile',
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="JSON file that specifies a filter of resources."
)]
[string] $FilterPath,
[Parameter(
Position=1,
ParameterSetName='JSONFile',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The action to perform on the RunSchedule tag, either Get, Set, or Remove."
)]
[Parameter(
Position=2,
ParameterSetName='CmdLine',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The action to perform on the RunSchedule tag, either Get, Set, Enable, Disable, or Remove."
)]
[ValidateSet("Get", "Set", "Enable", "Disable", "Remove")]
[string] $Action,
[Parameter(
Position=3,
ParameterSetName='CmdLine',
Mandatory=$False,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The new tag value."
)]
[string] $Tag
)
# Build an array of resource types currently supported.
$ResourceTypes = @("Microsoft.Compute/virtualMachines")
$ResourceTypes += "Microsoft.Sql/servers/databases"
$ResourceTypes += "Microsoft.AnalysisServices/servers"
# Get all of the resources in the subscription for the resource types supported
$allResources = @()
try {
$ResourceTypes | ForEach-Object {
$allResources += Get-AzureRMResource -WarningAction SilentlyContinue | Where-Object ResourceType -eq $_
}
# Get all of the resource groups in the subscription
$allResourceGroups = Get-AzureRmResourceGroup
}
catch {
$command = $_.InvocationInfo.MyCommand.Name
$ex = $_.Exception
$m =("{0} failed: {1}" -f $command, $ex.Message)
Throw $m
}
if ($PSCmdlet.ParameterSetName -eq "CmdLine") {
$filteredResources = $allResources | Where-Object {$_.ResourceGroupName -like $ResourceGroupName -and $_.Name -like $Name}
foreach ($resource in $filteredResources) {
# Retrieve the current tag on the resource
$tags = (Get-AzureRMResource -ResourceGroupName $resource.ResourceGroupName -Name $resource.Name).Tags
switch ($Action) {
"Set" {
if ($Tag.Length -gt 0) {
Set-Tag -Resource $resource -Tag $Tag
}
}
"Remove" {
Set-Tag -Resource $resource -Tag ""
}
"Enable" {
# Check if the RunSchedule tag does not exist
if ( ($tags -eq $Null) -or (-not ($tags.ContainsKey($script:TagRS))) ) {
# The tag doesn't exist
Write-Warning ("Can't enable! The {0} tag is not set for the resource {1}. Set the tag first." -f $script:TagRS, $resource.Name)
}
else {
$o = $tags.$script:TagRS | ConvertFrom-Json
# Only update the tag if enabled was disabled
if (-not ($o.Enabled) ) {
$o.Enabled = $true
$Tag = $o | ConvertTo-Json -Compress
Set-Tag -Resource $resource -Tag $Tag
}
}
}
"Disable" {
# Check if the RunSchedule tag does not exist
if ( ($tags -eq $Null) -or (-not ($tags.ContainsKey($script:TagRS))) ) {
# The tag doesn't exist
Write-Warning ("Can't disable! The {0} tag is not set for the resource {1}. Set the tag first." -f $script:TagRS, $resource.Name)
}
else {
$o = $tags.$script:TagRS | ConvertFrom-Json
# Only update the tag if enabled was enabled
if ($o.Enabled) {
$o.Enabled = $false
$Tag = $o | ConvertTo-Json -Compress
Set-Tag -Resource $resource -Tag $Tag
}
}
}
default {}
}
}
}
else {
# Initially set the filtered resources to all of the resources in the subscription
$filteredResources = $allResources
if ($FilterPath.Length -gt 0) {
if (Test-Path $FilterPath) {
# Import the JSON document
try {
$resourceJSON = Get-Content -Path $FilterPath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
}
catch {
$command = $_.InvocationInfo.MyCommand.Name
$ex = $_.Exception
Throw ("{0} failed: {1}" -f $command, $ex.Message)
}
# Create a filtered list of resources only if we have valid JSON data imported from the filter file
if ($resourceJSON -ne $null) {
# Reset the filtered list of resources to an empty array
$filteredResources = @()
foreach ($r in $resourceJSON.resourceGroups) {
$resourceGroups = $allResourceGroups | Where-Object {$_.ResourceGroupName -like $r.Name}
foreach ($rg in $resourceGroups) {
foreach ($res in $r.resources) {
$json = ""
# Get the RunSchedule JSON data if it exists for this resource node
if ([bool] ($res.PSObject.Properties.Name -match "RunSchedule") ) {
# The Status data is irrelevant in the filter file, so update the values in case the Action is Set
# Convert the object back to JSON
$json = $res.RunSchedule | ConvertTo-Json -Compress
}
$resources = $allResources | Where-Object {($_.ResourceGroupName -ieq $rg.ResourceGroupName -and $_.Name -ilike $res.Name -and $_.ResourceType -eq $res.resourceType)}
foreach ($resource in $resources) {
# Set the RunSchedule as it's set in the JSON file and the function was called with Action=Set
if ( ($json -ne $null) -and ($Action -eq "Set") ) {
Set-Tag -Resource $resource -Tag $json
}
# Remove the RunSchedule tag as the fuction was called with Action=Remove
if ($Action -eq "Remove") {
Set-Tag -Resource $resource -Tag ""
}
}
$filteredResources += $resources
}
}
}
}
}
}
}
# Output the array of resources that match the filter
$filteredResources
} # End function Find-Resources
function Wait-BackgroundJobs {
<#
.SYNOPSIS
Loops until Background jobs have completed
.DESCRIPTION
Loops until Background jobs have completed
.EXAMPLE
Wait-BackgroundJobs
.OUTPUTS
Output of Receive-Job cmdlet
#>
[CmdletBinding()]
Param()
# Set the maximum minutes before we give up and exit the while loop to avoid be stuck forever
$TimeOut = 15
# Get the current time
$StartTime = Get-Date
# Create an empty array list
[System.Collections.ArrayList] $Jobs = @()
# Add each job to the arraylist. Later they will be remove from the list one by one as they complete.
Get-Job | ForEach-Object {
$Jobs += $_
}
# Check job state in a loop. This script will not terminate until all jobs have completed or the timeout has expired.
while ($Jobs.Count -gt 0) {
# Check if timeout expired
if ( (New-TimeSpan $StartTime (Get-Date)).TotalMinutes -ge $TimeOut ) {
Write-Verbose ("{0} timed out. Returning to caller after {1} minutes" -f $MyInvocation.MyCommand, $TimeOut)
break
}
else {
for ($i = 0; $i -lt $Jobs.Count; $i++) {
switch ($Jobs[$i].State) {
"Completed" {
$ts = New-TimeSpan $Jobs[$i].PSBeginTime $Jobs[$i].PSEndTime
Write-Verbose ("Job id {0} completed in {1} seconds." -f $Jobs[$i].Id, $ts.TotalSeconds)
# Return job output to caller
Get-Job $Jobs[$i].Id | Receive-Job
Write-Debug ("Removing job id {0}" -f $Jobs[$i].id)
$Jobs[$i] | Remove-Job
$Jobs.RemoveAt($i)
$i--
}
"Failed" {
$ts = New-TimeSpan $Jobs[$i].PSBeginTime $Jobs[$i].PSEndTime
Write-Verbose ("Job id {0} failed in {1} seconds. Reason: {2}" -f $Jobs[$i].Id, $ts.TotalSeconds, $Jobs[$i].ChildJobs[0].JobStateInfo.Reason.Message)
# Return job output to caller
Get-Job $Jobs[$i].Id | Receive-Job
Write-Debug ("Removing job id {0}" -f $Jobs[$i].id)
$Jobs[$i] | Remove-Job
$Jobs.RemoveAt($i)
$i--
}
"Running" {
Write-Debug ("Job id {0} is still running." -f $Jobs[$i].Id)
}
default {
Write-Debug ("Job id {0} state is {1}." -f $Jobs[$i].Id, $Jobs[$i].State)
}
}
}
# Only sleep if there are still background jobs running.
if ($Jobs.Count -gt 0) {
# Sleep for a bit before checking jobs again. Some Azure actions take minutes to complete!
$seconds = 60
Write-Debug ("Sleeping for {0} seconds" -f $seconds)
Start-Sleep -Seconds $seconds
}
}
}
}
function Set-Tag {
<#
.SYNOPSIS
Sets the tag on a resource starting a background job in the process
.DESCRIPTION
Sets the tag on a resource starting a background job in the process
.PARAMETER Resource
A resource object
.PARAMETER Tag
The RunSchedule tag data in JSON compressed (minified) format.
If specified the tag will be updated on the resource.
If specified but a null string, the tag will be removed.
If not specified no action is taken on the tag.
.PARAMETER Wait
A switch argument. If specified, the tag will be set without starting a background job.
.EXAMPLE
Set-Tag -Resource $resource -Tag $Tag
.OUTPUTS
No outputs other than Write-Verbose
#>
[CmdletBinding()]
param (
[Parameter(
Position=0,
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The resource object."
)]
[object] $Resource,
[Parameter(
Position=1,
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="Update the tag with a new value. If null the tag will be removed."
)]
[string] $Tag
)
Write-Verbose ("Set-Tag called for Resource Id: {0}" -f $Resource.ResourceId)
Write-Debug ("New tag value: {0}" -f $Tag)
# Determine if the tag should be removed or set to a new value
$Remove = $False
if (-not ($PSBoundParameters.ContainsKey("Tag") ) ) {
Write-Debug "No tag was set"
return
}
else {
Write-Debug "Tag exists"
if ($Tag.Length -gt 0) {
Write-Debug "Tag is $Tag"
$Remove = $False
}
else {
$Remove = $True
}
}
$Tags = $Resource.Tags
if ($Remove) {
if ($Tags -eq $Null) {
Write-Verbose ("Nothing to do: There are no tags set for the resource {1}" -f $script:TagRS, $Resource.Name)
return
}
else {
# Check if the RunSchedule tag does not exist
if (-not ($Tags.ContainsKey($script:TagRS))) {
# The tag doesn't exist
Write-Verbose ("Nothing to do: The {0} tag is not set for the resource {1}" -f $script:TagRS, $Resource.Name)
return
}
}
# The tag exists so remove it
$Tags.Remove($script:TagRS)
}
else {
# Check if the tags property exists
if ($Tags -eq $Null) {
# Tags property didn't exist so set the tags to the single tag passed as a parameter
$Tags = @{$script:TagRS = $Tag}
}
else {
# Check if the RunSchedule tag already exists
if ($Tags.ContainsKey($script:TagRS) ) {
# The tag exists so update it
$Tags.Set_Item($script:TagRS, $Tag)
}
else {
# The tag doesn't exist in the tags collection so add a new tag
$Tags.Add($script:TagRS, $Tag)
}
}
}
# Get the path to the users credentials
$AProfile = $script:AzureProfile
Write-Debug ("Profile: {0}" -f $AProfile)
<#
Note that there are some problems with using the Set-AzureRmResource cmdlet to update tags:
1. Set-AzureRmResource hangs when an Analysis Services server is paused: https://github.com/Azure/azure-powershell/issues/4107
2. It takes longer to update tags with Set-AzureRmResource
3. Analysis Services and SQL databases must be running in order to update tags.
#>
# Create a script block unique to each resource type
switch ($Resource.ResourceType) {
"Microsoft.Compute/virtualMachines" {
$params = @{
ResourceGroupName = $Resource.ResourceGroupName
Name = $Resource.Name
}
$scriptBlock = Get-JobScriptBlock -Cmdlet Update-AzureRmVM
}
"Microsoft.Sql/servers/databases" {
# Split the ResourceName into the ServerName and DatabaseName components
$Name = $Resource.Name.Split("/")
$params = @{
ResourceGroupName = $Resource.ResourceGroupName
ServerName = $Name[0]
DatabaseName = $Name[1]
}
$scriptBlock = Get-JobScriptBlock -Cmdlet Set-AzureRmSqlDatabase
}
"Microsoft.AnalysisServices/servers" {
$params = @{
ResourceGroupName = $Resource.ResourceGroupName
Name = $Resource.Name
}
$scriptBlock = Get-JobScriptBlock -Cmdlet Set-AzureRmAnalysisServicesServer
}
}
if ($PSBoundParameters.ContainsKey("Wait") ) {
# Function was called with Wait switch - don't set the tag in a background job.
# Remove the "using" directive in the script block because it is not applicable to the Invoke-Command cmdlet
$sb = $scriptBlock.ToString() -replace '\$using\:', '$'
$sb = $sb -replace '\@using\:', '@'
$scriptBlock = [scriptblock]::Create($sb)
Invoke-Command -ScriptBlock $scriptBlock
}
else {
# Start a background job so that script doesn't block waiting for tag to be set
try {
$job = Start-Job -ScriptBlock $scriptBlock
} catch {
$command = $_.InvocationInfo.MyCommand.Name
$ex = $_.Exception
$m = ("{0} failed: {1}" -f $command, $ex.Message)
Throw $m
}
Write-Verbose ("Started job id {0} to update tags on Resource ID {1}." -f $job.Id, $Resource.ResourceId)
}
} # End function Set-Tag
function Get-ARMRunSchedule {
<#
.SYNOPSIS
Gets the run schedule for a given Azure RM resource.
.DESCRIPTION
Gets the run schedule for a given Azure RM resource.
.EXAMPLE
Get-ARMRunSchedule -SubscriptionId "24f94295-8632-4f38-bb71-4aa30c639634" -ResourceGroupName "rg-ubuntu01" -Name "ubuntu*"
.EXAMPLE
Get-ARMRunSchedule -SubscriptionId "24f94295-8632-4f38-bb71-4aa30c639634" -FilterPath ".\resourceFilter.json"
.PARAMETER SubscriptionId
The Azure subscription ID containing the resource.
.PARAMETER ResourceGroupName
The name of the resource group containing the resource.
.PARAMETER Name
The name of the resource.
.PARAMETER FilterPath
An optional JSON file that specifies a filter of resources, so that all resources in a subscription are not examined.
#>
[CmdletBinding(
DefaultParameterSetName="JSONFile"
)]
Param
(
[Parameter(
Position=0,
ParameterSetName='CmdLine',
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The Azure subscription ID containing the resource."
)]
[Parameter(
Position=0,
ParameterSetName='JSONFile',
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The Azure subscription ID containing the resource."
)]
[string] $SubscriptionId,
[Parameter(
Position=1,
ParameterSetName='CmdLine',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The name of the resource group containing the resource."
)]
[string] $ResourceGroupName,
[Parameter(
Position=2,
ParameterSetName='CmdLine',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The name of the resource."
)]
[string] $Name,
[Parameter(
Position=1,
ParameterSetName='JSONFile',
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="A JSON file that specifies a list of resources."
)]
[string] $FilterPath
)
# Make sure Azure sign on profile exists
if ($PSBoundParameters.ContainsKey("SubscriptionId") ) {
Save-ARMContext -SubscriptionId $SubscriptionId
}
else {
Save-ARMContext
}
# Determine which parameter set script was called with
if ($PSCmdlet.ParameterSetName -eq "CmdLine") {
$resources = Find-Resources -ResourceGroupName $ResourceGroupName -Name $Name -Action Get
# Make sure resources were found else display a warning message
if ($resources -eq $Null) {
Throw ("No resources were found where the resource group name was '{0}' and the resource name was '{1}'" -f $ResourceGroupName, $Name)
}
}
else {
if ( ($FilterPath -eq $Null) -or ($FilterPath -eq "") ) {
# Find all resources in the subscription since no filter file was specified.
$resources = Find-Resources -ResourceGroupName * -Name * -Action Get
}
else {
if (-not (Test-Path $FilterPath) ) {
Throw ("{0} is not a valid path." -f $FilterPath)
}
else {
# Find resources in the subscription that match the JSON in the filter file.
$resources = Find-Resources -FilterPath $FilterPath -Action Get
}
# Make sure resources were found else display a warning message
if ($resources -eq $Null) {
Write-Warning ("No resources were found. Check the JSON document '{0}'" -f $FilterPath)
return
}
}
}
# Create an empty array for the output
$resourceSchedules = @()
foreach ($resource in $resources) {
# Get the tags on the resource
$Tags = $resource.Tags
# Check if the RunSchedule tag does not exist
if ( ($Tags -eq $Null) -or (-not ($Tags.ContainsKey($script:TagRS))) ) {
# The tag doesn't exist
$object = New-Object psobject -Property @{
Name = $resource.Name
ResourceGroupName = $resource.ResourceGroupName
ResourceType = $resource.ResourceType
Enabled = $Null
AutoStart = $Null
RunDays = $Null
StartHourUTC = $Null
StartHourLocal = $Null
RunHours = $Null
Schedule = $Null
}
$resourceSchedules += $object
}
else {
# The tag exists so output the tag info
$o = $Tags.$script:TagRS | ConvertFrom-Json
# RunDays are special because they are stored as in array of ints. Cast them back to an array of System.DayOfWeek
$RunDays = [System.DayOfWeek[]] $o.RunDays
# Sort the RunDays because the script author has OCD
$RunDays = $RunDays | Sort-Object
# Get the name of the local time zone
$tzName = (Get-TimeZone).StandardName
# Get the current offset of local time from UTC time - this works for standard and daylight savings time.
$OffsetFromUTC = (Get-Date).Hour - ((Get-Date).ToUniversalTime()).Hour
# Convert the UTC hour to local hour
$StartHourLocal = $o.StartHourUTC + $OffsetFromUTC
if ($StartHourLocal -ge 24) {$StartHourLocal = $StartHourLocal - 24}
if ($StartHourLocal -lt 0) {$StartHourLocal = 24 + $StartHourLocal}
$dtStartLocal = [datetime] $($StartHourLocal.ToString() + ":00")
$EndHourLocal = $StartHourLocal + $o.RunHours
if ($EndHourLocal -ge 24) {$EndHourLocal = $EndHourLocal - 24 }
if ($EndHourLocal -lt 0) {$EndHourLocal = 24 + $EndHourLocal}
$dtEndLocal = [datetime] $($EndHourLocal.ToString() + ":00")
$Schedule = ("{0} to {1}, {2}" -f $dtStartLocal.ToShortTimeString(), $dtEndLocal.ToShortTimeString(), $tzName)
$object = New-Object psobject -Property @{
Name = $resource.Name
ResourceGroupName = $resource.ResourceGroupName
ResourceType = $resource.ResourceType
AutoStart = $o.AutoStart
Enabled = $o.Enabled
RunDays = [string]::Join(", ", $RunDays)
StartHourUTC = $o.StartHourUTC
StartHourLocal = $StartHourLocal
RunHours = $o.RunHours
Schedule = $Schedule
}
$resourceSchedules += $object
}
}
$resourceSchedules | Select-Object Name, ResourceGroupName, ResourceType, Enabled, AutoStart, StartHourUTC, StartHourLocal, RunHours, RunDays, Schedule
} # End function Get-ARMRunSchedule
function Set-ARMRunSchedule {
<#
.SYNOPSIS
Sets the run schedule for a given Azure RM resource.
.DESCRIPTION
Sets the run schedule for a given Azure RM resource.
.EXAMPLE
Set-ARMRunSchedule -SubscriptionId "24f94295-8632-4f38-bb71-4aa30c639634" `
-ResourceGroupName "rg-Management" -Name "AZEU1JEFFR01" -Enabled -AutoStart `
-RunHours 13 -RunDays Monday, Tuesday, Wednesday, Thursday, Friday -StartHourUTC 13
.EXAMPLE
Set-ARMRunSchedule -ResourceGroupName "rg-Management" -Name AZEU1JEFFR01 `
-Enabled -AutoStart -RunHours 13 -RunDays 1,2,3,4,5 -StartHourUTC 13
.PARAMETER SubscriptionId
The Azure subscription ID containing the resource.
.PARAMETER ResourceGroupName
The name of the resource group containing the resource.
.PARAMETER Name
The name of the resource.
.PARAMETER AutoStart
If this is set, the resource will be started each time it is "in schedule"
.PARAMETER Enabled
If this is set, the schedule is enabled, else it's disabled (will be preserved but ignored)
.PARAMETER RunHours
The number of hours the resource should run. RunHours+StartHourUTC
defines the hours of operation that the resource is considered
"in schedule".
.PARAMETER RunDays
The days of the week the resource should run
.PARAMETER StartHourUTC
The hour (in UTC) that the resource should be started.
.PARAMETER FilterPath
An optional JSON file that specifies a list of resources, so that all resources in a subscription are affected.
#>
[CmdletBinding(
DefaultParameterSetName="JSONFile"
)]
Param
(
[Parameter(
Position=0,
ParameterSetName='CmdLine',
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The Azure subscription ID containing the resource."
)]
[Parameter(
ParameterSetName='CmdLineEnabledOnly',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="Set this argument to true in order to automatically start the resource."
)]
[Parameter(
Position=0,
ParameterSetName='JSONFile',
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The Azure subscription ID containing the resource."
)]
[string] $SubscriptionId,
[Parameter(
ParameterSetName='CmdLine',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The name of the resource group containing the resource."
)]
[Parameter(
ParameterSetName='CmdLineEnabledOnly',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="Set this argument to true in order to automatically start the resource."
)]
[string] $ResourceGroupName,
[Parameter(
ParameterSetName='CmdLine',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The name of the resource."
)]
[Parameter(
ParameterSetName='CmdLineEnabledOnly',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="Set this argument to true in order to automatically start the resource."
)]
[string] $Name,
[Parameter(
ParameterSetName='CmdLine',
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="Set this argument to true in order to automatically start the resource."
)]
[switch] $AutoStart,
[Parameter(
ParameterSetName='CmdLine',
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="Set this argument to true in order to automatically start the resource."
)]
[Parameter(
ParameterSetName='CmdLineEnabledOnly',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="Set this argument to true in order to automatically start the resource."
)]
[switch] $Enabled,
[Parameter(
ParameterSetName='CmdLine',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The number of hours the resource should run."
)]
[int] $RunHours,
[Parameter(
ParameterSetName='CmdLine',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The days of the week the resource should run.")]
[System.DayOfWeek[]] $RunDays,
[Parameter(
ParameterSetName='CmdLine',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The hour (in UTC) that the resource should be started."
)]
[int] $StartHourUTC,
[Parameter(
Position=1,
ParameterSetName='JSONFile',
Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
HelpMessage="A JSON file that specifies a list of resources."
)]
[string] $FilterPath
)
# Make sure Azure sign on profile exists
if ($PSBoundParameters.ContainsKey("SubscriptionId") ) {
Save-ARMContext -SubscriptionId $SubscriptionId
}
else {
Save-ARMContext
}
# Determine which parameter set function was called with
switch ($PSCmdlet.ParameterSetName) {
"CmdLineEnabledOnly" {
if ($Enabled) {
$resources = Find-Resources -ResourceGroupName $ResourceGroupName -Name $Name -Action Enable
}
else {
$resources = Find-Resources -ResourceGroupName $ResourceGroupName -Name $Name -Action Disable
}
}
"JSONFile" {
# Check if filterpath exists
if ( $FilterPath.Length -gt 0) {
if (-not (Test-Path $FilterPath) ) {
Throw ("{0} is not a valid path." -f $FilterPath)
}
}
# Find resources in the subscription that match the JSON in the filter file.
$resources = Find-Resources -FilterPath $FilterPath -Action Set
# Make sure resources were found else display a warning message
if ($resources -eq $Null) {
Throw ("No resources were found. Check the JSON document '{0}'" -f $FilterPath)
}
}
"CmdLine" {
# Sort the RunDays because the script author has OCD
$RunDays = $RunDays | Sort-Object
# Create a hashtable of the parameters
$ht = @{
AutoStart = $AutoStart.IsPresent
Enabled = $Enabled.IsPresent
RunHours = $RunHours
RunDays = $RunDays
StartHourUTC = $StartHourUTC
}
# Convert the hashtable to JSON minified
$json = $ht | ConvertTo-Json -Compress
$resources = Find-Resources -ResourceGroupName $ResourceGroupName -Name $Name -Tag $json -Action Set
# Make sure resources were found else display a warning message
if ($resources -eq $Null) {
Throw ("No resources were found where the resource group name was '{0}' and the resource name was '{1}'" -f $ResourceGroupName, $Name)
}
}
}
}# End function Set-ARMRunSchedule
Function Remove-ARMRunSchedule {
<#
.SYNOPSIS
Removes the run schedule for a given Azure RM resource.
.DESCRIPTION
Removes the run schedule for a given Azure RM resource.
.EXAMPLE
> .\Remove-ARMRunSchedule.ps1 -SubscriptionId "24f94295-8632-4f38-bb71-4aa30c639634" `
-ResourceGroupName "rg-Management" -Name "AZEU1JEFFR01"
.PARAMETER SubscriptionId
The Azure subscription ID containing the resource.
.PARAMETER ResourceGroupName
The name of the resource group containing the resource.
.PARAMETER Name
The name of the resource.
.PARAMETER FilterPath
An optional JSON file that specifies a filter of resources, so that all resources in a subscription are not affected.
#>
[CmdletBinding(
DefaultParameterSetName="JSONFile"
)]
Param
(
[Parameter(
Position=0,
ParameterSetName='CmdLine',
Mandatory=$false,
ValueFromPipelineByPropertyName=$false,
HelpMessage="The Azure subscription ID containing the resource."