Get Azure cost for subscription including marketplace expenses with PowerShell

This will get last month consumption for a subscription including the money spend on marketplace.

$subscriptioname = "CHANGETHIS"
$roundDecimals = 2
$lastMonthBilling = (Get-Date).AddMonths(-1).ToString('yyyyMM')

# Set context to subscription
Set-azcontext -SubscriptionName $subscriptioname

# Get billing period
$BillingPeriod = Get-AzBillingPeriod -Name $lastMonthBilling
$startDate = $BillingPeriod.BillingPeriodStartDate.ToString("dd-MM-yyyy")
$endDate = $BillingPeriod.BillingPeriodEndDate.ToString("dd-MM-yyyy")

# Collect cost data
$currentCost = Get-AzConsumptionUsageDetail -StartDate $startDate -EndDate $endDate 
$currentCost += Get-AzConsumptionMarketplace -StartDate $startDate -EndDate $endDate

# Write output to screen
Write-Host "Current Cost of Subscription" (Get-AzContext).Subscription.Name ":" ([math]::Round(($currentCost | Measure-Object -Property PretaxCost -Sum).sum,$roundDecimals))

Get all subscriptions recursive from management groups with PowerShell

$topLvlMgmtGrp = "CHANGETHIS"          # Name of the top level management group
$subscriptions = @()                   # Output array

# Collect data from managementgroups
$mgmtGroups = Get-AzManagementGroup -GroupId $topLvlMgmtGrp -Expand -Recurse

$children = $true
while ($children) {
    $children = $false
    $firstrun = $true
    foreach ($entry in $mgmtGroups) {
        if ($firstrun) {Clear-Variable mgmtGroups ; $firstrun = $false}
        if ($entry.Children.length -gt 0) {
            # Add management group to data that is being looped throught
            $children       = $true
            $mgmtGroups    += $entry.Children
        else {
            # Add subscription to output object
            $subscriptions += New-Object -TypeName psobject -Property ([ordered]@{'DisplayName'=$entry.DisplayName;'SubscriptionID'=$entry.Name})


Force cancelation of subscription in Azure with REST call

Normally you can only cancel/disable a subscription by code if the subscription is empty.

If you add IgnoreResourceCheck=true and thereby still cancel the subscription. This give you the grace time before deletion. Remember to change {subscriptionId} in the URI{subscriptionId}/providers/Microsoft.Subscription/cancel?IgnoreResourceCheck=true&api-version=2021-10-01

Documentation on grace period

Azure function to test network connectivity on Hybrid/relay connection

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

$server = $Request.Query.Server
$port = $Request.Query.Port

try {  (new-object Net.Sockets.TcpClient).Connect($server,$port) }
catch { $closed = $true }

if ($closed) { Write-host "nogo"; $body = "nogo for " + $server + ":" + $port }
Else { Write-host "yeah" ; $body = "yeah, clear paths to "  + $server + ":" + $port }

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $body

Trigger Azure Policy to evaluate compliance

Can now be done with either Azure CLI

az policy state trigger-scan --resource-group !!!resource-group-name!!!

Or powershell

Start-AzPolicyComplianceScan -ResourceGroupName !!!resource-group-name!!!

Old school with API rest call

$subscriptionId = "!!!SUBSCRIPTION ID!!!"

$uri = "$subscriptionId/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation?api-version=2018-07-01-preview"
$azContext = Get-AzContext
$azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azProfile)
$token = $profileClient.AcquireAccessToken($azContext.Tenant.Id)
$authHeader = @{
    'Authorization'='Bearer ' + $token.AccessToken
Invoke-RestMethod -Method Post -Uri $uri -UseBasicParsing -Headers $authHeader

Azure role, start,stop and restart Virtual Machine

Json file, replace “/subscriptions/11111111-1111-1111-1111-111111111111” with your own subscription ID.

Save the Json file and run: az role definition create –role-definition filename.json

      "Name": "Virtual Machine Stop/Start/Restart",
      "IsCustom": true,
      "Description": "Can stop, start  and restart virtual machines.",
      "Actions": [
      "NotActions": [

      "AssignableScopes": [

Azure custom policy: Approved Costcenter Tag Values

Json for the rule. The tag could be something else. Just change the field: “tags.Costcenter”

  "mode": "All",
  "policyRule": {
    "if": {
      "not": {
        "field": "tags.Costcenter",
        "in": "[parameters('allowedTagValues')]"
    "then": {
      "effect": "deny"
  "parameters": {
    "allowedTagValues": {
      "type": "Array",
      "metadata": {
        "displayName": "Allowed tag values",
        "description": "The list of allowed Costcenter tag values"

Parameters when assigning the policy