Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PowerShell script used in an Azure Function to start all VMs in a resource group
#This Azure Function is used to start VMs within a resource group
# It was originally created for eplansTest virtual machines, as a self-service endeavor.
# Calling the Function manually:
<#
$Body = @"
{
"resourcegroup": "source-rg",
"action": "start",
"subscriptionid": "<subID>",
"tenantid": "<azure AD tenant ID"
}
"@
$URI = "https://hostname.azurewebsites.net/api/startVMs?code=FUNCTIONKEY"
Invoke-RestMethod -Uri $URI -Method Post -body $body
#>
using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
# Write to the Azure Functions log stream.
#Write-Host "PowerShell HTTP trigger function processed a request."
# Interact with query parameters or the body of the request.
$rgname = $Request.Query.resourcegroup
if (-not $rgname) {
$rgname = $Request.Body.resourcegroup
}
$action = $Request.Query.action
if (-not $action) {
$action = $Request.Body.action
}
$subscriptionid = $Request.Query.subscriptionid
if (-not $subscriptionid) {
$subscriptionid = $Request.Body.subscriptionid
}
$tenantid = $Request.Query.tenantid
if (-not $tenantid) {
$tenantid = $Request.Body.tenantid
}
#Proceed if all request body parameters are found
if ($rgname -and $action -and $subscriptionid -and $tenantid) {
$status = [HttpStatusCode]::OK
Select-AzSubscription -SubscriptionID $subid -TenantID $tenantid
if ($action -ceq "get") {
$body = Get-AzVM -ResourceGroupName $rgname -status | select-object Name, PowerState
}
if ($action -ceq "start") {
$body = $action
$body = Get-AzVM -ResourceGroupName $rgname | Start-AzVM -AsJob
}
}
else {
$status = [HttpStatusCode]::BadRequest
$body = "Please pass a name on the query string or in the request body."
}
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = $status
Body = $body
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.