Create Automation Action Group in Azure using powershell - azure

I want to use this command Set-AzActionGroup to action the standard automation runbook restart VM but there don't seem to be any examples of this around. To do this in Set-AzActionGroup I need to reference the VM, an automation account and some things called service uri and webhook resource id (which I think refers to the runbook). Has anyone got a fully specified example? I have a azure automation account but would need a webhook.

Just try the PowerShell below to create an Action group with restart VM AutomationRunbookReceiver:
$automationAccountResourceGroup = ""
$automationAccountName = ""
$webhookName = "Webhook20210316"
$receiverEmail = ""
$actionGroupName = ""
#create automationRunbookReceivers
$webhook = New-AzAutomationWebhook -Name $webhookName -IsEnabled $true -ExpiryTime "10/2/2030" -RunbookName "RestartAzureVmInResponseToVmAlertGlobalRunbook" -ResourceGroup $automationAccountResourceGroup -AutomationAccountName $automationAccountName -Force
$serviceURI = $webhook.WebhookURI
$automationAccountID = (Get-AzResource -ResourceGroup $automationAccountResourceGroup -name $automationAccountName).ResourceId
$WebhookResourceID = $automationAccountID + "/webhooks/" + $webhook.name
$AutomationRunbookReceiver = New-AzActionGroupReceiver -Name 'restartVM' -RunbookName 'Restart VM' -AutomationAccountId $automationAccountID.ToLower() -IsGlobalRunbook -AutomationRunbookServiceUri $serviceURI -WebhookResourceId $WebhookResourceID
#create email receivers
$EmailReceiver = New-AzActionGroupReceiver -Name $receiverEmail -EmailReceiver -EmailAddress $receiverEmail
Set-AzActionGroup -ResourceGroupName $automationAccountResourceGroup -Name $actionGroupName -ShortName $actionGroupName -Receiver $EmailReceiver,$AutomationRunbookReceiver
Result:
I also tested it on my side under some rules and it works as excepted:

Related

Why am I receiving a Connect-AzureAD error after connecting to the service?

I am working on my first GUI in Powershell. I have used small scripts with the Azure modules in the past so I am even more confused as to why this is breaking. In the script below there are two places that I tried to import and use the connect-azuread cmdlet so it is commented in the second spot but I attempted it in both places. The script is meant to present a GUI to select a csv of UPNs to find additional info in the azure tenant and return it in another csv. No matter where I place the connect-azuread command, I recieve the error: "You must call the Connect-AzureAD cmdlet before calling any other cmdlets." When I run the script it does prompt me to sign into Azure with the standard Microsoft login page but it apparently does not hold onto the credential.
This is the code that I tried:
Install-Module AzureAD -Force | Out-Null
Import-Module AzureAD | Out-Null
Connect-AzureAD
Add-Type -AssemblyName System.Windows.Forms
$LocationForm = New-Object system.Windows.Forms.Form
$LocationForm.ClientSize = '500,300'
$LocationForm.text = "Azure Information Pull"
$LocationForm.BackColor ='#ffffff'
$Title = New-Object System.Windows.Forms.Label
$Title.text = "Retrieving Data From Azure Tenant"
$Title.AutoSize = $true
$Title.Location = New-Object System.Drawing.Point(20,20)
$Title.Font = 'Microsoft Sans Serif,13'
$Description = New-Object System.Windows.Forms.Label
$Description.Text = "Retrieve UPN, Display Name, Email, and EmployeeID from Azure Tenant."
$Description.AutoSize = $False
$Description.Width = 450
$Description.Height = 50
$Description.location = New-Object System.Drawing.Point(20,50)
$Description.Font = 'Microsoft Sans Serif,10'
#$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog
#$FileBrowser.Title = "Select a file"
#$FileBrowser.InitialDirectory = [Environment]::GetFolderPath('Desktop')
#$FileBrowser.Filter = "CSV (*.csv)| *.csv"
#$SelectedFile = $FileBrowser.FileName
Function Get-FileName()
{
[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) |
Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = [Environment]::GetFolderPath('Desktop')
$OpenFileDialog.filter = "CSV (*.csv)| *.csv"
$OpenFileDialog.ShowDialog() | Out-Null
$global:Input = $OpenFileDialog.filename
$Input
} #end function Get-FileName
$InputFileBtn = New-Object System.Windows.Forms.Button
$InputFileBtn.BackColor = '#a4ba67'
$InputFileBtn.Text = "Select File"
$InputFileBtn.Width = 90
$InputFileBtn.height = 30
$InputFileBtn.Location = New-Object System.Drawing.Point(370,250)
$InputFileBtn.Font = 'Microsoft Sans Serif,10'
$InputFileBtn.ForeColor = "#ffffff"
$InputFileBtn.Add_Click({Get-FileName})
$cancelBtn = New-Object system.Windows.Forms.Button
$cancelBtn.BackColor = "#ffffff"
$cancelBtn.text = "Finish"
$cancelBtn.width = 90
$cancelBtn.height = 30
$cancelBtn.location = New-Object System.Drawing.Point(260,250)
$cancelBtn.Font = 'Microsoft Sans Serif,10'
$cancelBtn.ForeColor = "#000"
$cancelBtn.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$LocationForm.CancelButton = $cancelBtn
$LocationForm.Controls.AddRange(#($Title,$Description,$cancelBtn,$InputFileBtn))
[void]$LocationForm.ShowDialog()
#Begin Script
#Install-Module AzureAD -Force | Out-Null
#Import-Module AzureAD | Out-Null
#Connect-AzureAD
$OutputLocation = Split-Path -Path $global:Input
$UserList = import-csv -path $global:Input
foreach($user in $UserList){
Get-AzureADUser -ObjectID $user.upn | select UserPrincipalName,Displayname,mail, #{Name = 'EmployeeId'; Expression = {$_.ExtensionProperty.employeeId}} | export-csv "$OutputLocation\output.csv" -append -noTypeInformation}
I do not expect to get the error to connect to the azure ad module when I have already made the connection.
I tried to reproduce the same in my environment and got the results successfully like below:
Connect-AzureAD
Add-Type -AssemblyName System.Windows.Forms
$LocationForm = New-Object system.Windows.Forms.Form
$LocationForm.ClientSize = '500,300'
$LocationForm.text = "Azure Information Pull"
$LocationForm.BackColor ='#ffffff'
$Title = New-Object System.Windows.Forms.Label
$Title.text = "Retrieving Data From Azure Tenant"
$Title.AutoSize = $true
$Title.Location = New-Object System.Drawing.Point(20,20)
$Title.Font = 'Microsoft Sans Serif,13'
$Description = New-Object System.Windows.Forms.Label
$Description.Text = "Retrieve UPN, Display Name, Email, and EmployeeID from Azure Tenant."
$Description.AutoSize = $False
$Description.Width = 450
$Description.Height = 50
$Description.location = New-Object System.Drawing.Point(20,50)
$Description.Font = 'Microsoft Sans Serif,10'
[Environment]::GetFolderPath('Desktop')
Function Get-FileName()
{
[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) |
Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = [Environment]::GetFolderPath('Desktop')
$OpenFileDialog.filter = "CSV (*.csv)| *.csv"
$OpenFileDialog.ShowDialog() | Out-Null
$global:Input = $OpenFileDialog.filename
$Input
}
$InputFileBtn = New-Object System.Windows.Forms.Button
$InputFileBtn.BackColor = '#a4ba67'
$InputFileBtn.Text = "Select File"
$InputFileBtn.Width = 90
$InputFileBtn.height = 30
$InputFileBtn.Location = New-Object System.Drawing.Point(370,250)
$InputFileBtn.Font = 'Microsoft Sans Serif,10'
$InputFileBtn.ForeColor = "#ffffff"
$InputFileBtn.Add_Click({Get-FileName})
$cancelBtn = New-Object system.Windows.Forms.Button
$cancelBtn.BackColor = "#ffffff"
$cancelBtn.text = "Finish"
$cancelBtn.width = 90
$cancelBtn.height = 30
$cancelBtn.location = New-Object System.Drawing.Point(260,250)
$cancelBtn.Font = 'Microsoft Sans Serif,10'
$cancelBtn.ForeColor = "#000"
$cancelBtn.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$LocationForm.CancelButton = $cancelBtn
$LocationForm.Controls.AddRange(#($Title,$Description,$cancelBtn,$InputFileBtn))
[void]$LocationForm.ShowDialog()
$OutputLocation = Split-Path -Path $global:Input
$UserList = import-csv -path $global:Input
foreach($user in $UserList){
Get-AzureADUser -ObjectID $user.upn | select UserPrincipalName,Displayname,mail, #{Name = 'EmployeeId'; Expression = {$_.ExtensionProperty.employeeId}} | export-csv "$OutputLocation\output1.csv" -append -noTypeInformation}
The output file is exported successfully as below:
The error "You must call the Connect-AzureAD cmdlet before calling any other cmdlets" usually occurs if connection to the Azure AD Account is not successful.
Try Connect-AzureAD by using below command:
$credentials = Get-Credential
Connect-AzureAD -Credential $credentials
Otherwise, try to Connect Azure AD like below:
Connect-AzureAd -TenantId TenantID
If still the issue persists, try re-install the AzureAD module:
Uninstall-Module AzureAD
Install-Module AzureAD
Import-Module AzureAD

Using Azure Automation Account, Copy files from one Fileshare to another Fileshare across Storage

I am trying to copy one file (x) from a fileshare (y) of storage (z), to a fileshare (a) of storage (b).
$StorageAccountName = "z"
$StorageAccessKey =
"md226fZvTKPKaCd9TxDGPn4mitCPfvBvgzElwoqIgpbf2Pe09GKKfNJlMcK2EXXqRLqOrhBslybaE1Cpz2BcPg=="
$context1=New-AzureStorageContext $StorageAccountName $StorageAccessKey
$DestStorageAccountName = "b"
$DestStorageAccessKey = "xZjU0r5g5fU+/ieAbwc22OmVtFY5BJdQuF8OZsFd7hGHYLzQFGg9ZCpsVnQi5u6Wi/nigb8jdupUGo0YaXBphg=="
$destcontext1=New-AzureStorageContext $DestStorageAccountName $DestStorageAccessKey
$SrcPath = "https://z.file.core.windows.net/y/x"
$SrcShare = "y"
$DestPath = "https://b.file.core.windows.net/a"
$DestShare = "a"
Start-AzureStorageFileCopy -SrcFilePath $SrcPath -SrcShareName $SrcShare -DestShareName $DestShare -
DestFilePath $DestPath -Context $context1 -DestContext $destcontext1 -Force
It gives me error as below:
Start-AzStorageFileCopy: The given path/prefix 'https:' is not a valid name for a file or directory or does match the requirement for Microsoft Azure File Service REST API.
Thanks in Advance!
Please change the source and destination paths. In your particular scenario they should represent the path relative to the share.
$StorageAccountName = "z"
$StorageAccessKey =
"md226fZvTKPKaCd9TxDGPn4mitCPfvBvgzElwoqIgpbf2Pe09GKKfNJlMcK2EXXqRLqOrhBslybaE1Cpz2BcPg=="
$context1=New-AzureStorageContext $StorageAccountName $StorageAccessKey
$DestStorageAccountName = "b"
$DestStorageAccessKey = "xZjU0r5g5fU+/ieAbwc22OmVtFY5BJdQuF8OZsFd7hGHYLzQFGg9ZCpsVnQi5u6Wi/nigb8jdupUGo0YaXBphg=="
$destcontext1=New-AzureStorageContext $DestStorageAccountName $DestStorageAccessKey
$SrcPath = "test.txt" #assuming the name of the source file is "test.txt"
$SrcShare = "y"
$DestPath = "test.txt" #assuming you want to copy the file and keep the same name
$DestShare = "a"
Start-AzureStorageFileCopy -SrcFilePath $SrcPath -SrcShareName $SrcShare -DestShareName $DestShare -
DestFilePath $DestPath -Context $context1 -DestContext $destcontext1 -Force
From the documentation link:
-SrcFilePath Specifies the path of the source file relative to the source directory or source share.
-DestFilePath Specifies the path of the destination file relative to the destination share.

Why do I get error "Name or Service not known" when encrypting Azure VM?

I am trying to encrypt a VM in Azure using the following code
$keyVault = Get-AzureRmKeyVault –VaultName “azkeyvaultWestUS” -ResourceGroupName “azkeyvault”;
$diskEncryptionKeyVaultUrl = $keyVault.VaultUri;
$keyVaultResourceId = $keyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzureKeyVaultKey –VaultName “azkeyvaultWestUS” –Name “azpavdiskencryption”).Key.kid;
But when I tried to run it, I got the message
Get-AzKeyVaultKey: Name or Service not known
After the instruction ending in .Key.kid
Does anyone know how to fix this?
Thanks in advance.
Try accessing it separately and it should bye key.id
$Key = Add-AzureKeyVaultKey -VaultName "azkeyvaultWestUS" -Name 'azpavdiskencryption'
#get uri
$keyEncryptionKeyUrl = $Key.key.kid

Is there any problem with my query to get my token?

I'm trying to get an oauth token from my Azure AD using Powershell.
I try to generate my token into a text file to see the result for the 1rst step of my request.
I'm trying to get an Azure Digital Twins token. The constant you see in $resourceId is given by Microsoft to request AzureDigitalTwins.
And here is my script :
# Load ADAL methods
Add-Type -Path ".\MyPath\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$resultToken = ".\TokenTest.txt"
# Conf here
$aadInstance = "https://login.microsoftonline.com/"
$tenantId = "myTenantID"
$applicationId = "myAppID"
$applicationSecretKey = "myAppSecret"
$resourceId = "0b07f429-9f4b-4714-9392-cc5e8e80c8b0"
# Get an Access Token with ADAL
$authContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($aadInstance + $tenantId)
$clientCredential = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential($applicationId, $applicationSecretKey)
$authenticationResult = $authContext.AcquireTokenAsync($resourceId, $clientCredential)
($token = $authenticationResult.AccessToken) | Out-File $resultToken
After i run the script my Text file is empty but i get no error.
I use the exact same code in C# to get a token and it's working perfectly but not in Powershell apparently.
Is there a problem with this ?
Thanks for your answers.
Found the answer !
Just needed to add .GetAwaiter().GetResult() to the AcquireTokenAsync method !
$authenticationResult = $authContext.AcquireTokenAsync($resourceId, $clientCredential).GetAwaiter().GetResult()

Save-AzureRmVMImage mandatorily creates invalid blob container name

I am capturing an ARM VM image to use it in create from image operations.
However the Save-AzureRmVMImage command creates mandatorily (or just by default?) such a container and blob name what seems to be invalid for other commands.
The parts of "/Microsoft.Compute/ in the container name and "osDisk.xxxx" in the blob name are implicitly placed by the Save-AzureRmVMImage command.
To clarify:
I used the Save-AzureRmVMImage -DestinationContainerName 'vhds' -VHDNamePrefix 'template'... but the command creates the container system/Microsoft.Compute/Images/vhds + "invents" the blobname which contains the osdisk. (dot) part. Both of them are not coming from me... and can not be prevented-
First of all this name seems to be not usable in the New-AzureRmVM operation. (see my detailed description at Creating new ARM VM from captured image: Blob name in URL must end with '.vhd' extension error
As a workaround to the error described above I found out that I will copy theimage to an other blob name which does not contains . (dot). However it turned out that my fully tested and otherwise working copy script also throws error for that blob name...
Copy source code (again, it is fully functional for other blobs)
(note: This question about the Save-AzureRmVMImage issue, or how it can its weird and invalid name workarounded in subsequent operations. So the question is not about this copy script. The script here is just demonstrating a diagnostic experience.
Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionName "Visual Studio Premium with MSDN"
$sourceRgName = "rg-wp"
$sourceName = "mystorage"
$sourceContainerName = "system/Microsoft.Compute/Images/vhds" #the dots seems to be invalid
$sourceBlobName = "template-osDisk.be7b0cf4-a28b-47f9-89c7-43887f1570ab.vhd" #the dots seems to be invalid
$destinationRgName = "rg-wp"
$destinationName = "mystorage"
$destinationContainerName = "vhds"
$destinationBlobName = "template.vhd"
$sourceKeys = Get-AzureRmStorageAccountKey -Name $sourceName -ResourceGroupName $sourceRgName
$destinationKeys = Get-AzureRmStorageAccountKey -Name $destinationName -ResourceGroupName $destinationRgName
$contextSource = New-AzureStorageContext -StorageAccountName $sourceName -StorageAccountKey $sourceKeys.Key1
$contextDestination = New-AzureStorageContext -StorageAccountName $destinationName -StorageAccountKey $destinationKeys.Key1
Start-AzureStorageBlobCopy -Context $contextSource -SrcContainer $sourceContainerName -SrcBlob $sourceBlobName -DestContext $contextDestination -DestContainer $destinationContainerName -DestBlob $destinationBlobName
# Wait for copy to complete
Get-AzureStorageBlobCopyState -Context $contextDestination -Container $destinationContainerName -Blob $destinationBlobName -WaitForComplete
Full error message:
[ERROR] Start-AzureStorageBlobCopy : Container name 'system/Microsoft.Compute/Images/vh
[ERROR] ds' is invalid. Valid names start and end with a lower case letter or a number
[ERROR] and has in between a lower case letter, number or dash with no consecutive dash
[ERROR] es and is 3 through 63 characters long.
[ERROR] At D:\work\.vsonline\Azure\PowerShell\PowerShell\copy blob.ps1:40 char:1
[ERROR] + Start-AzureStorageBlobCopy -Context $contextSource -SrcContainer $sourceConta
[ERROR] ine ...
[ERROR] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[ERROR] ~~~
[ERROR] + CategoryInfo : NotSpecified: (:) [Start-AzureStorageBlobCopy],
[ERROR] ArgumentException
[ERROR] + FullyQualifiedErrorId : System.ArgumentException,Microsoft.WindowsAzure.
[ERROR] Commands.Storage.Blob.Cmdlet.StartAzureStorageBlobCopy
[ERROR]
The reason your code is failing is because the container name you're specifying in your script is invalid. Please see this link for a valid container name: https://msdn.microsoft.com/en-us/library/azure/dd135715.aspx.
Based on the information you provided in comments above, please try the following:
$sourceContainerName = "system"
$sourceBlobName = "Microsoft.Compute/Images/vhds/template-osDisk.be7b0cf4-a28b-47f9-89c7-43887f1570ab.vhd

Resources