0
votes

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)

1

1 Answers

0
votes

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.