How to reach a script file in a VM from Powershell runbook - azure

I have a script file in a VM that I want to reach from the azure portal in a Powershell runbook but it can't find the file. The file is manually saved in c:\ of the VM.
Code snippet in azure runbook:
IF ($VmAction -eq "Shutdown") {
try
{
Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroupName -VMName $VmName -CommandId 'RunPowerShellScript' -ScriptPath 'C:\\stopservice.ps1' -ErrorVariable result
Stop-AzVM -Name $VmName -ResourceGroupName $ResourceGroupName -Force
}
catch
{
throw "Error: $($_.Exception.Message)"
}
The command "Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroupName -VMName $VmName -CommandId 'RunPowerShellScript' -ScriptPath 'C:\stopservice.ps1' -ErrorVariable result" can be used on powershell on my computer so I think the issue is somewhere in Azure possibly.
script file (c:\stopservice.ps1):
try
{
Stop-Service -Name SSASTELEMETRY
}
catch
{
throw "Error: $($_.Exception.Message)"
}
(ps. the service name is for testing purposes, will stop different service when this works)

Have your Azure Automation runbook something like shown below. It should accomplish your requirement.
$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
Add-AzAccount -ServicePrincipal -TenantId $ServicePrincipalConnection.TenantId -ApplicationId $ServicePrincipalConnection.ApplicationId -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint
$rgname ="rrrrrrrrrrrrrr"
$vmname ="vvvvvvvvvvvvvv"
$ScriptToRun = "c:\test.ps1"
Out-File -InputObject $ScriptToRun -FilePath ScriptToRun.ps1
Invoke-AzVMRunCommand -ResourceGroupName $rgname -Name $vmname -CommandId 'RunPowerShellScript' -ScriptPath ScriptToRun.ps1
Remove-Item -Path ScriptToRun.ps1
Note: Before you run your runbook, make sure you update "rrrrrrrrrrrrrr" with your resource group name and "vvvvvvvvvvvvvv" with your VM name and also make sure you have the PowerShell named test.ps1 in C:\ drive of the VM.

Related

Passing parameter from Runbook Invoke-AzVMRunCommand to Powershell on VM

I'm trying to execute the Invoke-AzVMRunCommand in PowerShell and pass parameters to the script that needs to be executed.
Before I Run the Runbook I can define the parameter name:
Define Parameter
Code from the Runbook:
param(
[Parameter(Mandatory=$true)]
[string]$name
)
Write-Output "Connecting to azure via Connect-AzAccount -Identity"
Connect-AzAccount -Identity
Write-Output "Successfully connected with Automation account's Managed Identity"
Write-Output "Run Script Against Machines"
$ScriptToRun = "C:\testps.ps1"
Out-File -InputObject $ScriptToRun -FilePath ScriptToRun.ps1
Invoke-AzVMRunCommand -ResourceGroupName "RG" `
-VMName "VM" `
-CommandId 'RunPowerShellScript' `
-ScriptPath ScriptToRun.ps1 `
-Parameter #{"name" = $name}
Remove-Item -Path ScriptToRun.ps1
Script on the server I want to execute with the parameters:
param(
[string]$name
)
MKdir -Path "C:\Users" -Name $name
The script does not produce the expected output: Creating a folder with name from the parametr under C:\Users. No folder is being created.
If I execute the Invoke-AzVMRunCommand on the same script with hardcoded arguments like so:
MKdir -Path "C:\Users" -Name "TEST"
it does work and the folder gets created.
Firstly, I have script on VM and i have followed Microsoft-Document:
param(
[string]$name
)
MKdir -Path "C:\Users" -Name $name
Then i have used az invoke command in your script instead of Invoke-AzVMRunCommand and used below command:
az vm run-command invoke --command-id RunPowerShellScript --name "name of the VM" -g "name of the resourcegrp" --scripts "C:\test.ps1 $name"
Here $name is the param that you have send to runbook.
By this way you can create the folder with the name you want.
References taken from:
Executing Powershell script on Remote VM on Azure with Parameters - Stack Overflow
How to pass json file as parameter to Azure Powershell Runbook? - Stack Overflow

'Unauthorized' error creating app service plan

Don't know where exactly it is failing. I'm using VS Code to create the following script and running from there only:
$ResourceGroupName="powershell-grp"
$Location="North Europe"
$AppServicePlanName="PowershellAppService1975"
$WebAppName="PowershellWebApp1975"
Connect-AzAccount
Get-AzSubscription -SubscriptionName "Visual Studio Enterprise" | Select-AzSubscription
New-AzResourceGroup -Name $ResourceGroupName -Location $Location
New-AzAppServicePlan -Name $AppServicePlanName -Location $Location -Tier "B1" -NumberofWorkers 1 -ResourceGroupName $ResourceGroupName
New-AzWebApp -ResourceGroupName $ResourceGroupName -Name $WebAppName -Location $Location -AppServicePlan $AppServicePlanName
And in the powershell console, i get this error:
New-AzAppServicePlan: C:\Temp\AzureCmds\Azure Powershell-WebApp\Script1.ps1:9:1
Line |
9 | New-AzAppServicePlan -Name $AppServicePlanName -Location $Location -T …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Operation returned an invalid status code 'Unauthorized'
New-AzWebApp: C:\Temp\AzureCmds\Azure Powershell-WebApp\Script1.ps1:10:1
Line |
10 | New-AzWebApp -ResourceGroupName $ResourceGroupName -Name $WebAppName …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Operation returned an invalid status code 'Unauthorized'
Used -debug cmdlet option that gave the exact info on the issue.
The resource group location supported 0 instances for the chosen app service plan. Therefore, deployed app service plan and the web app to an altogether different location

How to enable storage account backup for app service / web app using powershell?

$sa=Get-AzStorageaccount -Name $storageAccountName -ResourceGroupName $resourceGroupName
$con=$sa.context
#newconatiner
New-AzStorageContainer -Context $con -Name $containerName -Permission off
#Get-azstoragecontainersastoken -Name $containerName -Context $con
#get uri
$r=New-azstoragecontainersastoken -Context $con -Name $containerName -Permission rwdl -FullUri
#enable storage backup
New-AzWebAppBackup -ResourceGroupName $resourceGroupName -Name $webappname -StorageAccountUrl $r
Edit-azwebappbackupconfiguration -ResourceGroupName $resourceGroupName -Name $webappname -FrequencyInterval $FrequencyInterval -FrequencyUnit $FrequencyUnit -RetentionPeriodInDays $RetentionPeriodInDays -StorageAccountUrl $r
The above lines of code throws an error saying storage access is denied.
Try these commands from the official MS document for Back up a web app using PowerShell
$webappname="mywebapp$(Get-Random -Minimum 100000 -Maximum 999999)"
$storagename="$($webappname)storage"
$container="appbackup"
$location="West Europe"
$backupname="backup1"
# Create a resource group.
New-AzResourceGroup -Name myResourceGroup -Location $location
# Create a storage account.
$storage = New-AzStorageAccount -ResourceGroupName myResourceGroup `
-Name $storagename -SkuName Standard_LRS -Location $location
# Create a storage container.
New-AzStorageContainer -Name $container -Context $storage.Context
# Generates an SAS token for the storage container, valid for one month.
# NOTE: You can use the same SAS token to make backups in Web Apps until -ExpiryTime
$sasUrl = New-AzStorageContainerSASToken -Name $container -Permission rwdl `
-Context $storage.Context -ExpiryTime (Get-Date).AddMonths(1) -FullUri
# Create an App Service plan in Standard tier. Standard tier allows one backup per day.
New-AzAppServicePlan -ResourceGroupName myResourceGroup -Name $webappname `
-Location $location -Tier Standard
# Create a web app.
New-AzWebApp -ResourceGroupName myResourceGroup -Name $webappname `
-Location $location -AppServicePlan $webappname
# Create a one-time backup
New-AzWebAppBackup -ResourceGroupName myResourceGroup -Name $webappname `
-StorageAccountUrl $sasUrl -BackupName $backupname
# List statuses of all backups that are complete or currently executing.
Get-AzWebAppBackupList -ResourceGroupName myResourceGroup -Name $webappname
Source for above PowerShell command is : https://learn.microsoft.com/en-us/azure/app-service/scripts/powershell-backup-onetime

Create VM in Azure from Private Image, and set Managed Data Disk names

In Azure, I have a private image which contains an OS disk, and multiple data disks.
When I use Azure Powershell to create a VM from the Private Image, I am able to set the name of the Managed OS disk, but I cannot find a way of setting the names of the Managed Data Disks, how can I do this?
This is my script so far:
# Configure the new Virtual Machine
$Vm = New-AzureRmVMConfig -VMName $SelectedConfig.VmName -VMSize $VmSize -Tags $SelectedConfig.Tag
$Vm = Set-AzureRmVMSourceImage -VM $Vm -Id $Image.Id
$Vm = Set-AzureRmVMOSDisk -VM $Vm -Name $SelectedConfig.OsDiskName -StorageAccountType Standard_LRS -DiskSizeInGB $SelectedConfig.OsDiskGB -CreateOption FromImage -Caching ReadWrite
$Vm = Set-AzureRmVMOperatingSystem -VM $Vm -Windows -ComputerName $SelectedConfig.ComputerName -Credential $Cred -ProvisionVMAgent -TimeZone $SelectedConfig.TimeZone
$Vm = Add-AzureRmVMNetworkInterface -VM $Vm -Id $nic.Id
$Vm = Set-AzureRmVMBootDiagnostics -VM $Vm -Enable -ResourceGroupName $SelectedConfig.Rsg -StorageAccountName $SelectedConfig.DiagStorageName
$Vm = New-AzureRmVM -VM $Vm -ResourceGroupName $SelectedConfig.Rsg -Location $Location -DisableBginfoExtension
you can use the following powershell cmdlet:
Add-AzVMDataDisk -VM $vm -Name %name_goes_here% -Lun $Lun `
-DiskSizeInGB 127 -CreateOption Empty
https://learn.microsoft.com/en-us/powershell/module/az.compute/add-azvmdatadisk?view=azps-3.1.0

Change SQL Connectivity in Azure using PowerShell

Is there a way to change/set SQL connectivity to Public(Internet) in a SQL Server azure vm while deploying sql vm or once deployed using powershell?
Part of my provisioning script looks like this. Will updating something in $vmConfig work?
# Create SQL Server
$vmConfig = New-AzureRmVMConfig -VMName $ServerName -VMSize 'Standard_D2_v2' | `
Set-AzureRmVMOperatingSystem -Windows -ComputerName $ServerName -Credential $adminCredentials -ProvisionVMAgent -EnableAutoUpdate | `
Set-AzureRmVMSourceImage -PublisherName "MicrosoftSQLServer" -Offer "SQL2017-WS2016" -Skus "SQLDEV" -Version "latest" | `
Set-AzureRmVMOSDisk -Name $osDiskName -VhdUri $osDiskUri -CreateOption "FromImage" | `
Add-AzureRmVMNetworkInterface -Id $nic.Id
# Add SQL Server VM extension
New-AzureRmVM -VM $vmConfig -ResourceGroupName $ResourceGroupName -Location $Location
Set-AzureRmVMSqlServerExtension -Name "SqlIaasExtension" -Version "1.2" -VMName $ServerName -ResourceGroupName $ResourceGroupName `
-Location $Location
Thank you

Resources