Condividi tramite


PowerShell script to execute commands in SCM website on all instances

Here is a quick PowerShell script to execute commands in SCM website on all instances.

For example, lets say you have a website running in an App Service Plan that has more than one instance and you would like to delete log files form all instances. You can log into KUDU console at <your website name>.scm.AzureWebsites.net and use Debug Console | CMD to delete log files. By default, KUDU console is connected to one of random instance. If you like to connect to another instance, you can follow these steps 

Another option is you can use below PowerShell scripts that will execute a CMD command on all instances :

 
#Login-AzureRmAccount

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

$env = @{
    command= 'Set COMPUTERNAME'
    dir= 'site'
}
$json = $env | 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
}