Azurearch Tech

Restart the Azure ADF machine

We need to stop the azure VM because azure cast each running cast based on used .hence we created powershell scripts to start to stop the Vms based on running .

param(
     [Parameter (Mandatory = $false)]
     [object] $WebhookData
 )

 $WebhookData  
  
 if($WebhookData){
     $parameters=(ConvertFrom-Json -InputObject $WebhookData.RequestBody) 
     if($parameters.callBackUri) {$callBackUri=$parameters.callBackUri}
 }


$VMAction=$parameters.VMAction
Write-Output $VMAction
$ResourceGroupName="ResourceGroupName"
$VirtualMachines="VirtualMachines"
$tenantId="tenantId"
$date = Get-Date
$day = [int]$date.day
Write-Host "Set int date........."
Write-Host 'Day of the month........'$day 
foreach ($VirtualMachine in $VirtualMachines)  
{
    Write-Output "Loop Running for Running for $($VirtualMachine)"
    #$myVirtualMachine = Get-AzAnalysisServicesServer -ResourceGroupName $ResourceGroupName -Name $VirtualMachine
	$pscredential = Get-AutomationPSCredential -Name 'dlake-pipeline-spn'
    Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId
	$VMDetail = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VirtualMachine  -Status
       
	foreach ($VMStatus in $VMDetail.Statuses)
	{ 
		  if ($VMStatus.Code -match "PowerState/")
		  {
			$VMStatusDetail = $VMStatus.DisplayStatus
		  }
		  else
		  {
			$VMStatusDetail = "Not Found"
		  }
}
	
	
    if (!$VMDetail)
    {
        Write-Error "$($VirtualMachine) not found in $($ResourceGroupName)"
        return
    }
    else
    {
        Write-Output "Current status of $($VirtualMachine): $($VMStatusDetail)"
    }
	#Start Azure VM
    if (($VMAction -eq "Start" -And $VMStatusDetail -eq "VM deallocated"))
    {
        Write-Output "Now starting $($VirtualMachine)"
        $null = Start-AzVM -ResourceGroupName $ResourceGroupName -Name $VirtualMachine
    }
    # Stop Azure VM
    elseif(($VMAction -eq "Stop" -And $VMStatusDetail -eq "VM running"))
    {
		Write-Output "Now Ready to stop $($VirtualMachine)"
		if ($day -ge 4)
		{
		    Write-Output "Now stopping $($VirtualMachine)"
			Write-Output "If block for stopping Server..day greater than $($day)" 
		    $null = Stop-AzVM -ResourceGroupName $ResourceGroupName -Name $VirtualMachine -Force
        }			
    }
	$body = [ordered]@{
    output = @{Message = "Success"}
    statusCode = "200"
    }

$bodyJson = $body | ConvertTo-Json

if($callBackUri){
    Invoke-WebRequest -Uri $callBackUri -UseBasicParsing -Method Post -Body $bodyJson -ContentType "application/json"
}
}

We can use above scripts and please create credential using SPN on azure active directly else its will ask each time to auththe resource

Exit mobile version