简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM