unable to create alert using powershell Add-AzMetricAlertRuleV2 - azure

I'm running into a weird issue here.
I'm trying to use powershell to create individual availbility alerts for all my storageaccounts.
My code is this
$storageaccounts= get-azstorageaccount |get-azresource
$criteria = New-AzMetricAlertRuleV2Criteria -MetricName "Availability" `
-TimeAggregation average `
-Operator lessthan `
-Threshold 100
foreach ($storageaccount in $storageaccounts){
Add-AzMetricAlertRuleV2 -Name "$storageaccount.Name availbility" `
-ResourceGroupName $RG.ResourceGroupName `
-WindowSize 00:05:00 `
-Frequency 00:01:00 `
-Description "Catching storageaccount availbility" `
-condition $criteria `
-ActionGroup $action `
-Severity 3 `
-TargetResourceId "$storageaccount.resourceid"
}
however I keep getting this error
Add-AzMetricAlertRuleV2 : Exception type: ErrorResponseException,
Message: Null/Empty, Code: Null, Status code:BadRequest, Reason phrase: Bad Request
I think the problem is due to
Add-AzMetricAlertRuleV2 -Name "$storageaccount.Name availbility"
if i put storageaccount.name into double quotation, i'm getting
Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResource.Name
I also tried this
foreach ($storageaccount in $storageaccounts){
$sa=[string]$storageaccount.Name
Add-AzMetricAlertRuleV2 -Name "$sa availbility"
but still gives me the same error
How can i fix this?

There are two problems in the command that you are using:
Name: You can pass the name as: "$($storageaccount.StorageAccountName) availbility"
Resource Id: Resource Id which you want to pass is stored in the property "id" of storage account not the "resourceId".
Updated code:
Add-AzMetricAlertRuleV2 -Name "$($storageaccount.StorageAccountName) availbility" `
-ResourceGroupName $RG.ResourceGroupName `
-WindowSize 00:05:00 `
-Frequency 00:01:00 `
-Description "Catching storageaccount availbility" `
-condition $criteria `
-ActionGroup $action `
-Severity 3 `
-TargetResourceId $storageaccount.id

Related

Azure PowerShell - New-AzWebAppCertificate doesn't return any response

I'm trying to use the New-AzWebAppCertificate cmdlet that creates a new certificate but I want to get the thumbprint after creation.
I have tried the following command that didn't work.
$certificate = New-AzWebAppCertificate -Name $apiName `
-ResourceGroupName $settings.resource `
-WebAppName $apiName `
-HostName $domainName `
-AddBinding -SslState 'SniEnabled' `
Write-Host $certificate.Thumbprint
But $certificate variable is empty.
Also, I've tried adding -OutVariable
New-AzWebAppCertificate -Name $apiName `
-ResourceGroupName $settings.resource `
-WebAppName $apiName `
-HostName $domainName `
-AddBinding -SslState 'SniEnabled' `
-OutVariable out
But still don't work..
If you read the documentation you will find that they are supporting common parameters such as -OutVariable and also the cmdlet produces PSCertificate output. But in fact, none of them are working.

How to add event subscription to Azure storage using New-AzEventGridSubscription?

I am trying to add subscription to storage account using New-AzEventGridSubscription. The subscription should be triggered by blob modification in a container and put message to a certain queue. I created the following script:
$ResourceGroup = "test"
$includedEventTypes = "Microsoft.Storage.BlobCreated", "Microsoft.Storage.BlobDeleted"
New-AzEventGridSubscription `
-ResourceId "/subscriptions/[id]/resourceGroups/[group]/providers/Microsoft.Storage/storageAccounts/[name]" `
-EventSubscriptionName DummyName `
-Endpoint "/subscriptions/[id]/resourceGroups/[group]/providers/Microsoft.Storage/storageAccounts/[name]/queueServices/default/queues/my-queue" `
-ResourceGroup $ResourceGroup `
-EndpointType "storagequeue" `
-SubjectBeginsWith "prefix" `
-SubjectEndsWith "suffix"
but it throws an error:
New-AzEventGridSubscription : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ New-AzEventGridSubscription `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-AzEventGridSubscription], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.Azure.Commands.EventGrid.NewAzureEventGridSubscription
I made similar command to add subscription to a custom topic, which worked well:
New-AzEventGridSubscription `
-ResourceGroup $ResourceGroup `
-EventSubscriptionName SubscriptionName `
-TopicName MyCustomTopic `
-EndpointType "storagequeue" `
-Endpoint "/subscriptions/[id]/resourceGroups/[group]/providers/Microsoft.Storage/storageAccounts/[account]/queueServices/default/queues/my-queue" `
-SubjectBeginsWith "prefix" `
-SubjectEndsWith "suffix"
I tried several modifications, but to no avail. What am I doing wrong?
After throwing out "ResourceGroup" parameter, reordering other parameters, and putting some arguments into variables, I finally managed to get my script up and running... If anyone ever needs similar stuff, here it is:
$subscriptionId = "<id>"
$ResourceGroup = "<group>"
$includedEventTypes = "Microsoft.Storage.BlobCreated", "Microsoft.Storage.BlobDeleted"
$storageAccount = "<account name>"
$endpoint = "/subscriptions/"+$subscriptionId+"/resourceGroups/"+$ResourceGroup+"/providers/Microsoft.Storage/storageAccounts/"+$storageAccount+"/queueServices/default/queues/my-queue"
$resourceId = "/subscriptions/"+$subscriptionId+"/resourceGroups/"+$ResourceGroup+"/providers/Microsoft.Storage/storageAccounts/"+$storageAccount
$subject = "prefix"
New-AzEventGridSubscription `
-EventSubscriptionName MySubscriptionName `
-Endpoint $endpoint `
-ResourceId $resourceId `
-EndpointType "storagequeue" `
-SubjectBeginsWith $subject `
-SubjectEndsWith "suffix" `
-IncludedEventType $includedEventTypes

Restoring a managed SQL instance in Azure using PowerShell

I am trying to figure out how to restore a database from one managed SQL instance to another. I'm following the tutorials, but I keep running into inscrutable error messages.
Here's my command:
Restore-AzSqlInstanceDatabase `
-Name "SomeDatabase" `
-InstanceName "our-oltp-dev" `
-ResourceGroupName "dev-managedsqlinstances" `
-PointInTime "4/7/2020 12:00:00" `
-TargetInstanceDatabaseName "SomeDatabase_FROM_DEV" `
-TargetInstanceName "our-oltp-sandbox" `
-TargetResourceGroupName "sandbox-managedsqlinstances"
Here's the output:
PS C:\WINDOWS\system32> Restore-AzSqlInstanceDatabase `
-Name "SomeDatabase" `
-InstanceName "our-oltp-dev" `
-ResourceGroupName "dev-managedsqlinstances" `
-PointInTime "4/7/2020 12:00:00" `
-TargetInstanceDatabaseName "SomeDatabase_FROM_DEV" `
-TargetInstanceName "our-oltp-sandbox" `
-TargetResourceGroupName "sandbox-managedsqlinstances"
Restore-AzSqlInstanceDatabase : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ Restore-AzSqlInstanceDatabase `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Restore-AzSqlInstanceDatabase], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.Azure.Commands.Sql.ManagedDatabase.Cmdlet.RestoreAzureRmSqlManagedDatabase
It's a copy-and-paste from the Azure docs; so I'm not sure what I'm doing wrong. Any help would be appreciated.
As mentioned in the comment, you need to pass the PointInTime as a DateTime instead of String, you could specify the 4/7/2020 12:00:00 as below.
Sample:
$PointInTime = Get-Date -Year 2020 -Month 4 -Day 7 -Hour 12 -Minute 0 -Second 0
Restore-AzSqlInstanceDatabase `
-Name "SomeDatabase" `
-InstanceName "our-oltp-dev" `
-ResourceGroupName "dev-managedsqlinstances" `
-PointInTime $PointInTime `
-TargetInstanceDatabaseName "SomeDatabase_FROM_DEV" `
-TargetInstanceName "our-oltp-sandbox" `
-TargetResourceGroupName "sandbox-managedsqlinstances"

Set-AzVMCustomScriptExtension in catch?

Attempting to add an extension when not detected but keep failing to find the secret sauce to get this to work. Mind you I am a BASH guy and this is a first foray into PowerShell..
#requires -version 2
# Required parameter $subscription: name of the subscription to enable Custom Script Extensions in
param (
# NOTE: See below for reason...
# [Parameter(Mandatory = $true)] [String] $subscription
# NOTE: Prompting is great for using the script interactively, but if this will also be executed
# from a build server or ...
# NOTE: Once the parameter is marked as mandatory PowerShell it will prompt for value. That said,
# if you remove the mandatory attribute then you can set a default value as a T_THROW ...
# NOTE: This _does_ contain shortcomings if this will be used as a pipeline param ...
# https://stackoverflow.com/questions/33600279/is-it-possible-to-force-powershell-script-to-throw-if-a-required-pipeline-para
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$SubscriptionName=$(Throw "`SubscriptionName` is mandatory, please provide a value...")
)
# Connect to the current Azure account
Write-Output "Pulling Azure account credentials..."
Start-Process "https://microsoft.com/devicelogin" # steals focus...
# Login to Azure account
Connect-AzAccount
# Set the active subscription
$null = Get-AzSubscription -SubscriptionName "$SubscriptionName" |Set-AzContext
# TODO: error handling
$vms = Get-AzVM
$cseName = "VulnerabilityManagementTools"
ForEach ($vm in $vms) {
try {
$cseStatus = Get-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Name $cseName `
-Status
}
catch {
Write-Output "Enabling Custom Script Extension for $vm."
Set-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroup `
-Location $vm.Location `
-VMName $vm.Name `
-Name $cseName `
-TypeHandlerVersion "1.1" `
-StorageAccountName "VulnerabilityManagementTools" `
-FileName "VulnerabilityManagementInstaller.ps1" `
-ContainerName "VulnerabilityManagementTools"
}
}
End up err'ing out with
PS /.../automation-scripts> ./EnableCustomScriptExtension.ps1 SubscriptionName
Pulling Azure account credentials...
WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXX to authenticate.
Account SubscriptionName TenantId Environment
------- ---------------- -------- -----------
XXXX#analytics.com SubName XXXXXX-XXXX AzureCloud
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{NAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{NAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/XXXXX/extensions/VulnerabilityManagementTools' under resource group '{RESOURCE_GROUPNAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{RESOURCE_GROUPNAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/{VMName}/extensions/VulnerabilityManagementTools' under resource group '{RESOURCEX_GROUPNAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/{VMName}/extensions/VulnerabilityManagementTools' under resource group '{RESOURCEX_GROUPNAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand`
In your case, you just need to use the if(){}else{} statement, try the script as below instead of the ForEach part of yours, it works fine on my side.
ForEach ($vm in $vms) {
$cseStatus = Get-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Name $cseName `
-Status `
-ErrorAction SilentlyContinue
if ($cseStatus){
Write-Host "The extension has been set for" $vm.Name
}else{
Write-Host "Enabling Custom Script Extension for" $vm.Name
Set-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroup `
-Location $vm.Location `
-VMName $vm.Name `
-Name $cseName `
-TypeHandlerVersion "1.1" `
-StorageAccountName "VulnerabilityManagementTools" `
-FileName "VulnerabilityManagementInstaller.ps1" `
-ContainerName "VulnerabilityManagementTools"
}
}
Test result:
You'll need to create an Azure AD Service Principal using password authentication and use the credentials of this to pass to the Connect-AzAccount cmdlet as follows:
$credentials = Get-Credential
Connect-AzAccount -ServicePrincipal -Credentials $credentials
The service account will need to have the necessary permissions to use the Set-AzVMCustomScriptExtensions cmdlet.
More information on creating the service account here:
https://learn.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-2.8.0

placing the results of Get-AzureRmVM into an array and using a loop to add them to the domain

I need to query a resource group for the number of VMs in the resource group, I then need to run the following command to add each machine to the domain.
In the below example I'm only adding server1 but if there are multiple servers in this resource group, whats the best way of ensuring each machine gets added based on the results of Get-AzureRmVM?
Set-AzureRmVMExtension -ResourceGroupName "abcd" -ExtensionType "JSONADDomainExtension" `
-Name "joindomain" -Publisher "Microsoft.Compute" -TypeHandlerVersion "1.0" `
-VMName "server1" -Location "uk west" -SettingString $string1 `
-ProtectedSettingString $String2
If you want to run Set-AzureRmVMExtension for each VM in a resource group, then you could run
$rg = "abcd"
# Fetch all the machines from one resource group
$machines = Get-AzureRmVM -ResourceGroupName $rg
# Loop over each object in the $machines array and add the extension
$machines | ForEach { Set-AzureRmVMExtension -ResourceGroupName $rg `
-ExtensionType "JSONADDomainExtension" -Name "joindomain" `
-Publisher "Microsoft.Compute" -TypeHandlerVersion "1.0" -VMName $_.Name `
-Location "uk west" -SettingString $string1 -ProtectedSettingString $String2 }

Resources