Partager via


PowerShell script to execute DOS commands using KUDU APIs

Lets say you would like to get the machine name from all VM instances that are running your Azure AppService website or you would like to create a folder under the wwwroot, this below sample PowerShell scripts can execute any DOS command

 
#Login-AzureRmAccount

$resoureGroupName = "wabac"
$websiteName = "wabacblue"

$env = @{
    command= 'Set COMPUTERNAME'
    dir= 'site'
}
$json = $env | ConvertTo-Json

$env2 = @{
    command= 'mkdir vdir'
    dir= 'site\wwwroot'
}
$json2 = $env2 | ConvertTo-Json

$website = Get-AzureWebsite -Name $websiteName
$username = $website.PublishingUsername
$password = $website.PublishingPassword
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
$apiBaseUrl = "https://$($website.Name).scm.azurewebsites.net/api"

[System.Uri]$Uri = $apiBaseUrl

$instances = Get-AzureRmResource -ResourceGroupName $resoureGroupName `
                                    -ResourceType Microsoft.Web/sites/instances `
                                    -ResourceName $websiteName `
                                    -ApiVersion 2018-02-01


foreach($instance in $instances)
{
    $instanceName = $instance.Name
    Write-Host "`tVM Instance ID `t`t: " $instanceName

    #Now execute 'SET COMPUTER' cmd
    $cookie= New-Object System.Net.Cookie
    $cookie.Name = "ARRAffinity"
    $cookie.Value = $instanceName
    $Cookie.Domain = $uri.DnsSafeHost
    $session=New-Object Microsoft.Powershell.Commands.WebRequestSession
    $session.Cookies.add($cookie)

    $response = Invoke-RestMethod -Uri "$apiBaseUrl/command" `
                                    -Headers @{Authorization=("Basic {0}" `
                                    -f $base64AuthInfo)} `
                                    -Method Post -Body $json `
                                    -ContentType 'application/json' `
                                    -WebSession $session
    Write-Host "`tVM Instance Name `t: " $response

    $response = Invoke-RestMethod -Uri "$apiBaseUrl/command" `
                                    -Headers @{Authorization=("Basic {0}" `
                                    -f $base64AuthInfo)} `
                                    -Method Post -Body $json2 `
                                    -ContentType 'application/json' `
                                    -WebSession $session
    Write-Host "`tCreate folder Results `t: " $response
}