Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
added more functions
function Update-PAzureAlertEmail
{
<#
.SYNOPSIS
This function either adds or removes an email from Alerts in azure
.DESCRIPTION
This function will remove the enclosed email from all the alerts in an azure subscription.
If ADD is specified it will add the email to the all the alerts in an azure subscription.
When this function is called it will return an object of the items that were added or removed.
.EXAMPLE
Update-AzureAlertEmail -Subscription 'your subscription name' -email 'youremail@youremail.com'
This will go to every alert in the subscription passed and update with the youremail@youremail.com address.
default behaviour for -actions is to perform an Add.
.EXAMPLE
Update-AzureAlertEmail -email 'youremail@youremail.com'
This will go to every alert in all your subscriptions and add the email address that was specified.
.EXAMPLE
Update-AzureAlertEmail -email 'youremail@youremail.com' -action remove
This will go to every alert in all your subscriptions and remove the email address that was specified.
.EXAMPLE
Update-AzureAlertEmail -Subscription 'your subscription name' -email 'youremail@youremail.com' -action remove
This will go to every alert in the subscription passed and remove with the youremail@youremail.com address.
#>
[CmdletBinding()]
param
(
[Parameter(Position=0)]
[Object]
$Subscriptions = (Get-AzureRmSubscription),
[Parameter(Mandatory=$true)][string]$email,
[ValidateSet('Add', 'Remove')]
[string]$action = 'Add'
)
Begin
{
if((($Subscriptions | Get-Member).TypeName | Select-Object -Unique) -eq 'Microsoft.Azure.Commands.Profile.Models.PSAzureSubscription')
{
$subs = $Subscriptions
}
else
{
$subs = get-AzureRmSubscription -subscriptionname $subscriptions
}
$Updated = $null
$AlertsUpdated = @()
}
Process
{
ForEach ($SubName in $Subs)
{
$null = Set-AzureRmContext -SubscriptionName ($SubName.SubscriptionName)
$alerts = get-AzureRmResource | Where-Object{$_.resourcetype -like '*alert*'}
#azure web tests https://azure.microsoft.com/en-us/blog/creating-a-web-test-alert-programmatically-with-application-insights/
foreach($alert in $alerts)
{
Write-Progress -Activity Updating -Status ('{0} ->' -f $action) -PercentComplete ($alerts.IndexOf($alert)) -CurrentOperation $alert.name
if($action -eq 'Add')
{
$Updated = Add-PAzureEmailAlertRule -Subscriptionname $subname.subscriptionName -ResourceGroupName $alert.ResourceGroupName -location $alert.Location -name $alert.Name -email $email
$AlertsUpdated += $Updated
}
elseif($action -eq 'Remove')
{
$Updated = Remove-PAzureEmailAlertRule -Subscriptionname $subname.subscriptionName -ResourceGroupName $alert.ResourceGroupName -location $alert.Location -name $alert.Name -email $email
$AlertsUpdated += $Updated
}
}
$AlertsUpdated
}
}
}
function Get-PAzureAlertEmail
{
<#
.SYNOPSIS
this function will get all alerts for the subscription passed.
.DESCRIPTION
This function will retreive all the alerts for the subscription passed. It will return an object with the Name of the alert
a property named emails that will contain the alerts for that email.
Resourcetype, ResourceGroupName, ResourceID, SubscriptionName, SubscriptionID and the location of the alert.
.EXAMPLE
get-pazurealertemail -Subscriptions 'azure testing'
This will get all the alerts for the azure testing subscription.
.EXAMPLE
get-pazurealertemail -Subscriptions 'azure testing' -email 'youremail@youremail.com' -find
This will search through all alerts to find an alert that has the email specified in it.
Each alert that is found it'll return them when the function completes.
#>
[CmdletBinding()]
param
(
[Parameter(Position=0)]
[Object]
$Subscriptions = (Get-AzureRmSubscription),
[string]$email,
[switch]$find
)
Begin
{
if((($Subscriptions | Get-Member).TypeName | Select-Object -Unique) -eq 'Microsoft.Azure.Commands.Profile.Models.PSAzureSubscription')
{
$subs = $Subscriptions
}
else
{
$subs = get-AzureRmSubscription -subscriptionname $subscriptions
}
}
Process
{
ForEach ($SubName in $Subs)
{
Set-AzureRmContext -SubscriptionName ($SubName.SubscriptionName) | out-null
$alerts = get-AzureRmResource | Where-Object{$_.resourcetype -like '*alert*'}
#azure web tests https://azure.microsoft.com/en-us/blog/creating-a-web-test-alert-programmatically-with-application-insights/
foreach($alert in $alerts)
{
if($find -and $email -ne $null -or $email -ne '')
{$action = ('Searching for {0}' -f $email)}
else{$action = 'Gathering all alerts'}
Write-Progress -Activity Searching -Status ('{0} ->' -f $action) -PercentComplete ($alerts.IndexOf($alert)) -CurrentOperation $alert.name
#$targetResourceId = ((Get-AzureRmAlertRule -Name $alert[0].name -ResourceGroup $alert[0].ResourceGroupName).tags[1].key -replace 'hidden-link:','')
#https://docs.microsoft.com/en-us/azure/monitoring-and-diagnostics/insights-alerts-powershell#comments-container
$targetResourceId = get-azurermalertrule -ResourceGroup $alert.ResourceGroupName -Name $alert.Name -DetailedOutput
$alertSetup = ($targetResourceId).properties.condition
$actions = $targetResourceId.properties.Actions
if($actions -eq 0)
{ $emails = ''}
else
{
$emailActions = $targetResourceId.properties.Actions.Count -1
$emails = $actions[$emailActions].customemails
}
if($find -and $email -ne $null -or $email -ne '')
{
if($emails -contains $email)
{
[PSCustomObject]@{
'Name' = $alert.Name
'Emails'= $emails
'ResourceType' = $alert.ResourceType
'ResourceGroupName' =$alert.ResourceGroupName
'ResourceId' = $alert.ResourceId
'SubscriptionName' = $subname.SubscriptionName
'SubscriptionId' = $Subname.SubscriptionId
'Location' = $alert.Location
} #PSCustomObject
}
}
else
{
[PSCustomObject]@{
'Name' = $alert.Name
'Emails'= $emails
'ResourceType' = $alert.ResourceType
'ResourceGroupName' =$alert.ResourceGroupName
'ResourceId' = $alert.ResourceId
'SubscriptionName' = $subname.SubscriptionName
'SubscriptionId' = $Subname.SubscriptionId
'Location' = $alert.Location
}
}
}
}
}
}
function Add-PAzureEmailAlertRule
{
<#
.SYNOPSIS
Adds an email for an alert in Azure.
.DESCRIPTION
This script will an an email to an existing alert. It will not add email addresses to Web Test type alerts or Smart Detection type alerts. It only operates on standard metric alerts.
.EXAMPLE
Add-PAzureAlertRule -subscriptionName 'your subscription' -resourcegroup 'resource group' -location 'US West' -name 'Name of the alert' -email 'emailToadd@youemailserver.com'
.EXAMPLE
Add-PAzureAlertRule -subscriptionName 'your subscription' -resourcegroup 'resource group' -location 'US West' -name 'Name of the alert' -email 'emailToadd@youemailserver.com'
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Subscription Name that the alert is a part of')]
[ValidateNotNullOrEmpty()]
[string]$Subscriptionname,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Resource group name that the alert belongs to')]
[ValidateNotNullOrEmpty()]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Location in Azure where the alert is used.')]
[ValidateNotNullOrEmpty()]
[string]$location,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Actual name of the alert')]
[ValidateNotNullOrEmpty()]
[Alias('alertname')]
[string]$name,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Email Address that will be added to the alert')]
[ValidateNotNullOrEmpty()]
[string]$email
)
Begin
{
if((get-azurermcontext).Subscription.SubscriptionName -ne $Subscriptionname)
{
$null = set-azurermcontext -Subscriptionname $Subscriptionname
}
}
Process
{
#$targetResourceId = ((Get-AzureRmAlertRule -Name $alert[0].name -ResourceGroup $alert[0].ResourceGroupName).tags[1].key -replace 'hidden-link:','')
#https://docs.microsoft.com/en-us/azure/monitoring-and-diagnostics/insights-alerts-powershell#comments-container
write-verbose -Message "checking to see if an email is set. If not we'll set it and update the send to true"
$addedEmail = $false
$targetResourceId = (get-azurermalertrule -ResourceGroup $ResourceGroupName -Name $Name -DetailedOutput)
#$alertSetup = ($targetResourceId).properties.condition
$actions = $targetResourceId.properties.Actions
$alertSetup = ($targetResourceId).properties.condition
if($actions.count -eq 0)
{
$targetresourceId.properties.actions.add((new-azurermAlertRuleEmail -CustomEmails $email ))
$targetresourceid.properties.actions[($targetresourceid.properties.actions.count -1)].SendToServiceOwners = $true
$addedEmail = $true
}
else
{
$emailActions = $targetResourceId.properties.Actions.Count -1
$emails = $actions[$emailActions].customemails
if($emails -notcontains $email)
{
$targetResourceId.properties.actions[$emailActions].customemails.add($email)
$addedEmail = $true
}
}
#$sendtoServiceOwners = $actions[1].sendtoserviceowners
#$targetResourceId.properties.actions[$emailActions].CustomEmails
if($addedEmail)
{
if($targetResourceId.properties.Description -eq $null -or $targetResourceId.properties.Description -eq '')
{
$description = 'Added by Automation'
}
else
{
$description = $targetResourceId.properties.Description
}
Write-verbose -Message ('updating {0} in ResourceGroup {1}' -f ($Name), ($ResourceGroupName))
write-verbose -Message ('{0}' -f $Location)
if($alertSetup.threshold -ne $null -and $alertsetup.TimeAggregation -ne $null) #if operator is not present we assume it is a web test.
{
$found = Test-PAzureAlertSource -Subscriptionname $subscriptionName -ResourceGroupName $ResourceGroupName -location $location -name $name
#try{
# write-verbose "don't set the alert if we can't find the target"
# $null = get-azurermresource -resourceid $alertSetup.DataSource.ResourceUri
# $found = $true
# }
#catch{ $found = $false}
if($found)
{
add-azurermmetricalertrule -name $Name -Location $Location -ResourceGroup $ResourceGroupName -operator $alertSetup.operator -Threshold ($alertSetup.threshold) -TargetResourceId $alertSetup.DataSource.ResourceUri -MetricName $alertSetup.DataSource.MetricName -WindowSize $alertSetup.WindowsSize -TimeAggregationOperator $alertsetup.TimeAggregation -Description $description -Actions $targetResourceId.properties.Actions #-Debug
}
else
{
$addedEmail = $false
write-warning -Message ('cannot find ResourceID: {0}' -f $alertSetup.DataSource.ResourceUri)
}
}
elseif($alertsetup.TimeAggregation -eq $null)
{
write-verbose -Message ('Time Aggregation is null cannot add email to {0}' -f $name)
$addedemail = $false
}
else
{
write-verbose -Message ('An alert email cannnot be setup for {0} as it is a web test' -f $name)
#Add-AzureRmWebtestAlertRule -Name "webtestRule" -Location "East US" -ResourceGroup "Default-Web-EastUS" -WindowSize 00:05:00 -MetricName "metric" -TargetResourceUri ":/subscriptions/b67f7fec-69fc-4974-9099-a26bd6ffeda3/resourcegroups/Default-Web-WestUS/providers/microsoft.insights/webtests/leowebtestr1-webtestr1" -Description "Nice Webtest rule" -Failed 3
#add-AzureRmWebtestAlertRule -name $Name -Location $Location -ResourceGroup $ResourceGroupName -WindowSize $alertSetup.WindowSize -metricName $alertsetup.datasource.metricname -TargetResourceUri $alertSetup.DataSource.ResourceUri -Description $description -failed $alertSetup.FailedLocationCount #-Debug
$addedEmail = $false
}
}
if($addedEmail -eq $true)
{$targetResourceId}
else
{$targetresourceid =$null}
$targetresourceid
}
}
function Remove-PAzureEmailAlertRule
{
<#
.SYNOPSIS
Removes an email for an alert in Azure.
.DESCRIPTION
This script will remove an email from an existing alert. It will not remove email addresses from Web Test type alerts or Smart Detection type alerts. It only operates on standard metric alerts.
.EXAMPLE
Remove-PAzureAlertRule -subscriptionName 'your subscription' -resourcegroup 'resource group' -location 'US West' -name 'Name of the alert' -email 'emailToadd@youemailserver.com'
.EXAMPLE
Remove-PAzureAlertRule -subscriptionName 'your subscription' -resourcegroup 'resource group' -location 'US West' -name 'Name of the alert' -email 'emailToadd@youemailserver.com'
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Subscription Name that the alert is a part of')]
[ValidateNotNullOrEmpty()]
[string]$Subscriptionname,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Resource group name that the alert belongs to')]
[ValidateNotNullOrEmpty()]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Location in Azure where the alert is used.')]
[ValidateNotNullOrEmpty()]
[string]$location,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Actual name of the alert')]
[ValidateNotNullOrEmpty()]
[Alias('alertname')]
[string]$name,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Email Address that will be removed from the alert')]
[ValidateNotNullOrEmpty()]
[string]$email
)
Begin
{
if((get-azurermcontext).Subscription.SubscriptionName -ne $Subscriptionname)
{
$null = set-azurermcontext -Subscriptionname $Subscriptionname
}
}
Process
{
#$targetResourceId = ((Get-AzureRmAlertRule -Name $alert[0].name -ResourceGroup $alert[0].ResourceGroupName).tags[1].key -replace 'hidden-link:','')
#https://docs.microsoft.com/en-us/azure/monitoring-and-diagnostics/insights-alerts-powershell#comments-container
write-verbose -Message "checking to see if an email is set. If not we'll set it and update the send to true"
$removedEmail = $false
$targetResourceId = (get-azurermalertrule -ResourceGroup $ResourceGroupName -Name $Name -DetailedOutput)
#$alertSetup = ($targetResourceId).properties.condition
$actions = $targetResourceId.properties.Actions
$alertSetup = ($targetResourceId).properties.condition
$emailActions = $targetResourceId.properties.Actions.Count -1
$emails = $actions[$emailActions].customemails
if($emails -contains $email)
{
$targetResourceId.properties.actions[$emailActions].customemails.Remove($email)
$removedEmail = $true
}
#$sendtoServiceOwners = $actions[1].sendtoserviceowners
#$targetResourceId.properties.actions[$emailActions].CustomEmails
if($removedEmail)
{
if($targetResourceId.properties.Description -eq $null -or $targetResourceId.properties.Description -eq '')
{
$description = 'Added by Automation'
}
else
{
$description = $targetResourceId.properties.Description
}
Write-verbose -Message ('updating {0} in ResourceGroup {1}' -f ($Name), ($ResourceGroupName))
write-verbose -Message ('{0}' -f $Location)
if($alertSetup.threshold -ne $null -and $alertsetup.TimeAggregation -ne $null)
{
$found = Test-PAzureAlertSource -Subscriptionname $subscriptionName -ResourceGroupName $ResourceGroupName -location $location -name $name
#try{
# write-verbose "don't set the alert if we can't find the target"
# $null = get-azurermresource -resourceid $alertSetup.DataSource.ResourceUri
# $found = $true
# }
#catch{ $found = $false}
if($found)
{
add-azurermmetricalertrule -name $Name -Location $Location -ResourceGroup $ResourceGroupName -operator $alertSetup.operator -Threshold ($alertSetup.threshold) -TargetResourceId $alertSetup.DataSource.ResourceUri -MetricName $alertSetup.DataSource.MetricName -WindowSize $alertSetup.WindowsSize -TimeAggregationOperator $alertsetup.TimeAggregation -Description $description -Actions $targetResourceId.properties.Actions #-Debug
$removedEmail = $true
}
else
{
$removedEmail = $false
write-warning -Message ('cannot find ResourceID: {0}' -f $alertSetup.DataSource.ResourceUri)
}
}
elseif($alertsetup.TimeAggregation -eq $null)
{
write-verbose -Message ('Time Aggregation is null cannot remove email from {0}' -f $name)
$removedEmail = $false
}
else
{
write-verbose -Message ('An alert email cannnot be setup for {0} as it is a web test' -f $name)
#Add-AzureRmWebtestAlertRule -Name "webtestRule" -Location "East US" -ResourceGroup "Default-Web-EastUS" -WindowSize 00:05:00 -MetricName "metric" -TargetResourceUri ":/subscriptions/b67f7fec-69fc-4974-9099-a26bd6ffeda3/resourcegroups/Default-Web-WestUS/providers/microsoft.insights/webtests/leowebtestr1-webtestr1" -Description "Nice Webtest rule" -Failed 3
#add-AzureRmWebtestAlertRule -name $Name -Location $Location -ResourceGroup $ResourceGroupName -WindowSize $alertSetup.WindowSize -metricName $alertsetup.datasource.metricname -TargetResourceUri $alertSetup.DataSource.ResourceUri -Description $description -failed $alertSetup.FailedLocationCount #-Debug
$removedEmail = $false
}
}
if($removedEmail -eq $true)
{$targetResourceId}
else
{$targetresourceid = $null}
$targetresourceid
}
}
function Test-PAzureAlertSource
{
<#
.SYNOPSIS
Tests to see if the alert source is valid for an alert in Azure.
.DESCRIPTION
This function will return a $true if the alert source is valid and found in azure. If if it is found that the alert source is invalid then it'll will return a false.
.EXAMPLE
Test-PAzureAlertSource -subscriptionName 'your subscription' -resourcegroup 'resource group' -location 'USWest' -name 'Name of the alert'
.EXAMPLE
Test-PAzureAlertSource -subscriptionName 'your subscription' -resourcegroup 'resource group' -location 'USWest' -name 'Name of the alert'
#>
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Subscription Name that the alert is a part of')]
[ValidateNotNullOrEmpty()]
[string]$Subscriptionname,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Resource group name that the alert belongs to')]
[ValidateNotNullOrEmpty()]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Location in Azure where the alert is used.')]
[ValidateNotNullOrEmpty()]
[string]$location,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Actual name of the alert')]
[ValidateNotNullOrEmpty()]
[Alias('alertname')]
[string]$name
)
Begin
{
if((get-azurermcontext).Subscription.SubscriptionName -ne $Subscriptionname)
{
$null = set-azurermcontext -Subscriptionname $Subscriptionname
}
}
Process
{
$targetResourceId = (get-azurermalertrule -ResourceGroup $ResourceGroupName -Name $Name -DetailedOutput)
#$alertSetup = ($targetResourceId).properties.condition
$valid = $false
try{
write-verbose -Message "don't set the alert if we can't find the target"
$null = get-azurermresource -resourceid $targetResourceId.properties.condition.datasource.resourceuri
$found = $true
}
catch{ $found = $false}
$found
}
}
function Remove-PAzureOrphanedAlerts
{
<#
.SYNOPSIS
Removes orphaned alerts from a subscription
.DESCRIPTION
This function will find all alerts in an azure subscription and remove them if the corresponding Asset that is being monitored no longer exists.
.EXAMPLE
Remove-PAzureOrphanedAlerts -Subscriptions 'Azure Testing'
Will return an object of all alerts that were removed.
.EXAMPLE
Remove-PAzureOrphanedAlerts
Will return an object of all alerts that have been removed for all subscriptions that the current user/entity can reach.
#>
[CmdletBinding(SupportsShouldProcess=$True, ConfirmImpact = 'Medium')]
param
(
[Parameter(Position=0)]
[Object]
$Subscriptions = (Get-AzureRmSubscription)
)
Begin
{
if((($Subscriptions | Get-Member).TypeName | Select-Object -Unique) -eq 'Microsoft.Azure.Commands.Profile.Models.PSAzureSubscription')
{
$subs = $Subscriptions
}
else
{
$subs = get-AzureRmSubscription -subscriptionname $subscriptions
}
$Updated = $null
$AlertsUpdated = @()
if ($ConfirmPreference -eq 'Low') {
<#
User:
* selected -Confirm
* has $Global:ConfirmPreference set to Low.
#>
$YesToAll = $false
}
else {
# No -Confirm, so we won't prompt the user…
$YesToAll = $true
}
# NoToAll is always $false - we want to give it a try…
$NoToAll = $false
}
Process
{
$action = 'Remove'
ForEach ($SubName in $Subs)
{
$null = Set-AzureRmContext -SubscriptionName ($SubName.SubscriptionName)
$alerts = get-AzureRmResource | Where-Object{$_.resourcetype -like '*alert*'}
#azure web tests https://azure.microsoft.com/en-us/blog/creating-a-web-test-alert-programmatically-with-application-insights/
foreach($alert in $alerts)
{
$status = $null
Write-Progress -Activity Updating -Status ('from Subscription {1} {0} ->' -f $action,$subName.SubscriptionName) -PercentComplete ($alerts.IndexOf($alert)) -CurrentOperation $alert.name
if(!(Test-PAzureAlertSource -Subscriptionname $SubName.SubscriptionName -ResourceGroupName $alert.ResourceGroupName -location $alert.location -name $alert.name))
{
write-verbose "removing $($alert.name) from $($SubName.SubscriptionName) in Resource group: $($alert.ResourceGroupName) "
$targetResourceId = get-azurermalertrule -ResourceGroup $alert.ResourceGroupName -Name $alert.Name -DetailedOutput
if($PSCmdlet.ShouldProcess("Removed the Alert - '$($alert.Name)'",
"Remove the alert '$($alert.Name)'?",
"Removing Alert" ))
{
if($Force -Or $PSCmdlet.ShouldContinue("Are you REALLY sure you want to remove '$($alert.Name)'?", "Removing '$($alert.Name)'", [ref]$YesToAll, [ref]$NoToAll))
{$status = Remove-AzureRmAlertRule -ResourceGroup $alert.ResourceGroupName -name $alert.name }
}
}
if($status -ne $null)
{$AlertsUpdated += $targetResourceId}
}
}
$AlertsUpdated
}
}
function Get-PAzureOrphanedAlerts
{
<#
.SYNOPSIS
Gets orphaned alerts from a subscription
.DESCRIPTION
This function will find all alerts in an azure subscription and return those orphaned alert names in an object.
.EXAMPLE
Get-PAzureOrphanedAlerts -Subscriptions 'Azure Testing'
Will return an object of all alerts that are orphaned.
.EXAMPLE
Remove-PAzureOrphanedAlerts
Will return an object of all alerts that are orphaned for each subscription that the user can get to.
#>
[CmdletBinding()]
param
(
[Parameter(Position=0)]
[Object]
$Subscriptions = (Get-AzureRmSubscription)
)
Begin
{
if((($Subscriptions | Get-Member).TypeName | Select-Object -Unique) -eq 'Microsoft.Azure.Commands.Profile.Models.PSAzureSubscription')
{
$subs = $Subscriptions
}
else
{
$subs = get-AzureRmSubscription -subscriptionname $subscriptions
}
$Updated = $null
$AlertsUpdated = @()
}
Process
{
ForEach ($SubName in $Subs)
{
$action = 'Get'
$null = Set-AzureRmContext -SubscriptionName ($SubName.SubscriptionName)
$alerts = get-AzureRmResource | Where-Object{$_.resourcetype -like '*alert*'}
#azure web tests https://azure.microsoft.com/en-us/blog/creating-a-web-test-alert-programmatically-with-application-insights/
foreach($alert in $alerts)
{
$status = $null
Write-Progress -Activity Getting -Status ('from Subscription {1} {0} ->' -f $action,$subName.SubscriptionName) -PercentComplete ($alerts.IndexOf($alert)) -CurrentOperation $alert.name
if(!(Test-PAzureAlertSource -Subscriptionname $SubName.SubscriptionName -ResourceGroupName $alert.ResourceGroupName -location $alert.location -name $alert.name))
{
write-verbose "removing $($alert.name) from $($SubName.SubscriptionName) in Resource group: $($alert.ResourceGroupName) "
$targetResourceId = get-azurermalertrule -ResourceGroup $alert.ResourceGroupName -Name $alert.Name -DetailedOutput
$status = $true
}
if($status -ne $null)
{$AlertsUpdated += $targetResourceId}
}
}
$AlertsUpdated
}
}
Function Format-OrphanedAlerts
{
<#
.SYNOPSIS
Takes an Orphand Alert Object and creates a flattened data set.
.DESCRIPTION
if Get-PAzureOrphanedAlerts is piped to this function it will return an object that is flattened. This object contains the following information:
Name of the alert
SourceResourceID = This is the thing that is being watched by the alert. Which is no longer in Azure (orphaned).
ResourceId = This is the resourceId that is associated with the alert.
emails = These are the email addresses that are associated with the Alert if present
Name : PulteWebSqlMasterLogIoPercent
SourceResourceId : /subscriptions/4a41ecf5-7683-49a5-8f1a-53ce28b8152a/resourceGroups/PulteWebProd/providers/Microsoft.Sql/servers/pulteweb/databases/PulteWebMaster
ResourceId : /subscriptions/4a41ecf5-7683-49a5-8f1a-53ce28b8152a/resourceGroups/PulteWebProd/providers/microsoft.insights/alertrules/PulteWebSqlMasterLogIoPercent
emails : youremailaddress@yourcompany.com
.EXAMPLE
Get-PAzureOrphanedAlerts -Subscriptions 'Azure Testing'
Will return an object of all alerts that are orphaned.
.EXAMPLE
Remove-PAzureOrphanedAlerts
Will return an object of all alerts that are orphaned for each subscription that the user can get to.
#>
param(
[object]$OrphanedAlerts
)
$formattedAlerts= $OrphanedAlerts | select @{n='Name';e={$_.properties.name}}, @{n='SourceResourceId';e={$_.properties.Condition.datasource.resourceuri}}, @{n = 'ResourceId';e={$_.id}}, @{n='emails';e={$_.properties.actions.customemails -join ','}}
$formattedAlerts
}
#select name,@{n="Emails";e={($_.emails) -join ','}},subscriptionName
@crshnbrn66

This comment has been minimized.

Copy link
Owner Author

@crshnbrn66 crshnbrn66 commented Nov 28, 2016

Updated logic in the get pazurealertemail

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment