Last active
July 18, 2023 12:59
-
-
Save ljtill/7136beb57c6738bad2c1c8572d8a5360 to your computer and use it in GitHub Desktop.
Provides the ability to execute scripts against Virtual Machines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Invoke-AzureRmVMRunCommand { | |
| <# | |
| .SYNOPSIS | |
| Invoke-AzureRmVMRunCommand will provide the ability to execute scripts against Virtual Machines. | |
| .DESCRIPTION | |
| Provides the ability to execute script files against Virtual Machines | |
| .EXAMPLE | |
| Invoke-AzureRmVMRunCommand -SubscriptionId $subscriptionId -ResourceGroupName $resourceGroupName -VirtualMachineName $virtualMachineName -ScriptPath $scriptPath -AccessToken $accessToken -Verbose | |
| #> | |
| [CmdletBinding()] | |
| param ( | |
| [Parameter()] | |
| [string]$SubscriptionId, | |
| [Parameter()] | |
| [string]$ResourceGroupName, | |
| [Parameter()] | |
| [string]$VirtualMachineName, | |
| [Parameter()] | |
| [string]$ScriptPath, | |
| [Parameter()] | |
| [string]$AccessToken | |
| ) | |
| begin { | |
| $apiVersion = "2018-06-01" | |
| } | |
| process { | |
| $request = @{ | |
| Uri = ("https://management.azure.com/subscriptions/" + $subscriptionId + "/resourceGroups/" + $resourceGroupName + "/providers/Microsoft.Compute/virtualMachines/" + $virtualMachineName + "/runCommand?api-version=" + $apiVersion) | |
| Method = "POST" | |
| Headers = @{ | |
| "Authorization" = ("Bearer " + $accessToken) | |
| "Content-Type" = "application/json" | |
| "Accept" = "application/json" | |
| } | |
| Body = @{ | |
| "commandId" = "RunPowerShellScript" | |
| "script" = ([string[]](Get-Content -Path $ScriptPath)) | |
| } | ConvertTo-Json | |
| } | |
| $response = Invoke-WebRequest @request | |
| $request = @{ | |
| Uri = ($response.Headers.'Azure-AsyncOperation')[0] | |
| Method = "GET" | |
| Headers = @{ | |
| "Authorization" = ("Bearer " + $accessToken) | |
| "Accept" = "application/json" | |
| } | |
| Body = $null | |
| } | |
| do { | |
| $response = Invoke-WebRequest @request | |
| Start-Sleep -Seconds 5 | |
| } while (($response.Content | ConvertFrom-Json).status -eq "InProgress") | |
| $output = (($response.Content | ConvertFrom-Json).properties.output.value.message).Replace("\n", "`n") | |
| } | |
| end { | |
| return $output | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment