Home > Net >  Run Powershell commands with API request, PUT request
Run Powershell commands with API request, PUT request

Time:03-01

https://docs.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,

CodePudding user response:

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

CodePudding user response:

You can also use the Invoke-AzRestMethod cmdlet to execute the PUT operation using the existing context. Consult the reference documentation for more details: https://docs.microsoft.com/powershell/module/az.accounts/invoke-azrestmethod

Alternatively, if the goal is to run a command on a VM, you can also consider using the Invoke-AzVMRunCommand cmdlet as described here: https://docs.microsoft.com/powershell/module/az.compute/invoke-azvmruncommand.

  • Related