Search code examples
restazure-powershellazure-vmruncommand

Run Powershell commands with API request, PUT request


https://learn.microsoft.com/en-us/rest/api/compute/virtual-machine-run-commands/create-or-update#request-body

Could you please give an implementation example to apply the steps at the above documentation? I couldn't figure out what are the steps and how to apply.

Thanks in advance,


Solution

  • I'm going at this blind since I can't use my companies Azure Environment to test but in the least this will be a good start for you to be able to troubleshoot.

    I set all the requested information as variables so that you can change them as you see fit. The part that is most questionable here is how Azure wants you to do the authorization header.

    On the page you linked there is an option to "Try this" on that menu you should be able to build a custom API request and it will include the headers there.

    Let me know how this does and I can help troubleshoot if there are issues.

    $runcommandname = ""
    $subscriptionId = ""
    $resourcegroupname = ""
    $vmName = ""
    
    $apiKey = ""
    $resource = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourcegroupname/providers/Microsoft.Compute/virtualMachines/$vmName/runCommands/$runcommandname"
    $apiversion = "?api-version=2021-07-01"
    $resource = $resource + $apiversion
    
    $authHeader = @{
        'Authorization' = "apiToken $apiKey"
    }
    
    
    Invoke-RestMethod -Method Put -Uri $resource -H $authHeader