-
Notifications
You must be signed in to change notification settings - Fork 15
/
Set-AzRgTags.ps1
172 lines (154 loc) · 6.84 KB
/
Set-AzRgTags.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
<#
.SYNOPSIS
Set tag keys and values on Resource Groups based upon a list provided from a csv file (use ',' as delimiter).
.DESCRIPTION
REQUIRED : Internet access & Already connected to an Azure tenant
REQUIRED : PowerShell modules, see variables
REQUIRED : Contributor privileges on the resource you want to tag
.PARAMETER CsvFilePath
Mandatory
Columns : Subscription Name,Resource Group Name,tagkey1,tagkey2,tagkey3,tagkey4,tagkey....
.PARAMETER LogFile
Optional
Log file path
.NOTES
AUTHOR: James Dumont le Douarec
.LINK
https://github.com/JamesDLD/AzureRm-PowerShell
.EXAMPLE
./Set-AzRgTags.ps1 -CsvFilePath "./logs/30-10-2020-Get-AzRgTags.ps1.csv"
#>
param(
[Parameter(Mandatory = $true, HelpMessage = 'Csv file path')]
[String]
$CsvFilePath,
[Parameter(Mandatory = $false, HelpMessage = 'Log file path')]
[String]
$LogFile
)
################################################################################
# Function
################################################################################
#region function
Function Generate_Log_Action([string]$Action, [ScriptBlock]$Command, [string]$LogFile) {
$Output = "Info : $Action ... "
Write-Host $Output -ForegroundColor Cyan
((Get-Date -UFormat "[%d-%m-%Y %H:%M:%S] : ") + "Info" + " : " + $Action) | Out-File -FilePath $LogFile -Append -Force
Try {
$Result = Invoke-Command -ScriptBlock $Command
}
Catch {
$ErrorMessage = $_.Exception.Message
$Output = "On action $Action : $ErrorMessage"
((Get-Date -UFormat "[%d-%m-%Y %H:%M:%S] : ") + "Error" + " : " + $Output) | Out-File -FilePath $LogFile -Append -Force
Write-Error $Output
$Result = "Error"
}
Return $Result
}
#endregion
################################################################################
# Variable
################################################################################
Set-StrictMode -Version 2
$ErrorActionPreference = "Stop"
$workfolder = Split-Path $script:MyInvocation.MyCommand.Path
$date = Get-Date -UFormat "%d-%m-%Y"
$p=1 #Pourcentage
$Warnings=@()
#Module Name, Minimum Version
$PowerShellModules = @(
("Az.Accounts", "1.7.5"),
("Az.Resources", "1.13.0")
)
#If not provided, creating the log file
if ($LogFile -eq "") {
$LogPath = $workfolder + "\logs"
if (!(Test-Path $LogPath)) { mkdir $LogPath }
$logFile = $LogPath + "\$date-" + $MyInvocation.MyCommand.Name + ".log"
}
ForEach ($PowerShellModule in $PowerShellModules) {
$Action = "Importing the Module $($PowerShellModule[0]) with MinimumVersion $($PowerShellModule[1])"
$Command = { Import-Module $PowerShellModule[0] -MinimumVersion $($PowerShellModule[1]) -ErrorAction Stop }
$Result = Generate_Log_Action -Action $Action -Command $Command -LogFile $logFile
if ($Result -eq "Error") { Exit 1 }
}
#endregion
$Action = "Importing the csv file $CsvFilePath"
$Command = { Import-Csv $CsvFilePath -ErrorAction Stop }
$CsvRgs = Generate_Log_Action -Action $Action -Command $Command -LogFile $logFile
if ($CsvRgs -eq "Error") { Exit 1 }
################################################################################
# Action
################################################################################
foreach($CsvRg in $CsvRgs)
{
#Variables
$SubscriptionName = $CsvRg.'Subscription Name'
$RgName = $CsvRg.'Resource Group Name'
$TargetTagsFromCsv = $CsvRg | Get-Member -MemberType NoteProperty | Where-Object { $_.Name -ne 'Subscription Name' -and $_.Name -ne 'Resource Group Name' -and $_.Name -ne 'Resource Group Location'}
$TargetTags = New-Object System.Collections.Hashtable
foreach($TargetTagFromCsv in $TargetTagsFromCsv)
{
$TagKey=$TargetTagFromCsv.Name
if($CsvRg.$($TargetTagFromCsv.Name))
{
$TagValue=$CsvRg.$($TargetTagFromCsv.Name)
}else{
$TagValue="to_be_determined"
}
$TargetTags.Add($TagKey,$TagValue) | Out-Null
}
Write-Progress -Activity "Parsing subscription : $SubscriptionName, checking tags on Resource Group : $RgName" -Status "Progress:" -PercentComplete (($p / @($CsvRgs).Count) *100);
$p++
#Authentication
$AzContext = Get-AzContext
if($null -eq $AzContext)
{
$Action = "Signing in with Azure PowerShell"
$Command = { Connect-AzAccount -ErrorAction Stop }
$Result = Generate_Log_Action -Action $Action -Command $Command -LogFile $logFile
if ($Result -eq "Error") { Exit 1 }
$AzContext = Get-AzContext
}
if($AzContext.Subscription.Name -ne $SubscriptionName)
{
$Action = "Setting the Azure context for the subscription $SubscriptionName"
$Command = {Get-AzSubscription -SubscriptionName $SubscriptionName | Set-AzContext -ErrorAction Stop}
$AzureRmContext = Generate_Log_Action -Action $Action -Command $Command -LogFile $logFile
if($AzureRmContext -eq "Error"){Exit 1}
$Action = "Selecting the Azure the subscription $SubscriptionName"
$Command = {Select-AzSubscription -Name $SubscriptionName -Context $AzureRmContext -Force -ErrorAction Stop}
$AzSubscription = Generate_Log_Action -Action $Action -Command $Command -LogFile $logFile
if($AzSubscription -eq "Error"){Exit 1}
}
$Action = "Getting the Resource Group : $RgName"
Write-Host "Info : $Action ... " -ForegroundColor Cyan
((Get-Date -UFormat "[%d-%m-%Y %H:%M:%S] : ") + "Info" + " : " + $Action) | Out-File -FilePath $LogFile -Append -Force
try{
$ResourceGroup = Get-AzResourceGroup -Name $RgName -ErrorAction Stop
$resourcetags=$ResourceGroup.Tags
if($resourcetags)
{
$Action = "Merging current tags with wished tags on the Resource Group : $RgName"
$Command = {Update-AzTag -ResourceId $ResourceGroup.ResourceId -Tag $TargetTags -Operation Merge -ErrorAction Stop}
$Result = Generate_Log_Action -Action $Action -Command $Command -LogFile $logFile
if($Result -eq "Error"){Exit 1}
}else{
$Action = "Adding new wished tags on the Resource Group : $RgName"
$Command = {New-AzTag -ResourceId $ResourceGroup.ResourceId -Tag $TargetTags -ErrorAction Stop}
$Result = Generate_Log_Action -Action $Action -Command $Command -LogFile $logFile
if($Result -eq "Error"){Exit 1}
}
}
catch{
$WarningMessage="Not updating Resource group $RgName in subscription : $SubscriptionName because of the error message : $($_.Exception.Message)"
$Warnings+=$WarningMessage
((Get-Date -UFormat "[%d-%m-%Y %H:%M:%S] : ") + "Warning" + " : " + $WarningMessage) | Out-File -FilePath $LogFile -Append -Force
}
}
if($Warnings)
{
Write-Host "Warning" -ForegroundColor Yellow
$Warnings
}