Azure function that returns HTTP status code and text string

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
$body = "<html><body>"

# 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.
$InputString += $Request.Query.TextString
if ($InputString -eq $null) {$InputString = "Default string"}
$body += $InputString

$body += "<br><p>Version: 11</p>"
$body += "</body></html>"

$statusCode = $Request.Query.StatusCode
if ($statusCode -eq $null) {$statusCode = "OK"}

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::$statusCode
    ContentType = "text/html"
    Body = $body
})

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})
        }
    }
}

$subscriptions

Powershell script to activate client KMS on Windows Server

# Elevate to adm
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
 if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
  $CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
  Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
  Exit
 }
}

# Find OS
$OS = (Get-WMIObject win32_operatingsystem).Caption

if ($OS.Length -lt 2) { Write-host -ForegroundColor Yellow "Unable to determine OS"; Break}
Else { Write-host -ForegroundColor Green "$OS"}

# Find domain and check DNS
$Domain = (Get-WmiObject win32_computersystem).Domain
$DnsOutPUT = Resolve-DnsName -Name _vlmcs._tcp.$domain -Type SRV -ErrorAction SilentlyContinue
if ($DnsOutPUT.Length -lt 2) { Write-host -ForegroundColor Yellow "Unable to determine DNS records for KMS"; Break}

Else { Write-host -ForegroundColor Green "KMS server(s): " $DnsOutPUT.NameTarget}

# Test connectivity to KMS servers
foreach ( $KMSserver in $DnsOutPUT.NameTarget ) {
if ((Test-NetConnection -ComputerName $KMSserver -Port 1688 -ErrorAction SilentlyContinue).TcpTestSucceeded) { Write-host -ForegroundColor Green "Succesfully connected to:" $KMSserver}
}


# Build Array of KMS keys - https://docs.microsoft.com/en-us/windows-server/get-started/kms-client-activation-keys
$kmsKeys = @()
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2022 Datacenter";'Key'="WX4NM-KYWYW-QJJR4-XV3QB-6VM33" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2022 Standard";'Key'="VDYBN-27WPP-V4HQT-9VMD4-VMK7H" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2019 Datacenter";'Key'="WMDGN-G9PQG-XVVXX-R3X43-63DFG" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2019 Standard";'Key'="N69G4-B89J2-4G8F4-WWYCC-J464C" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2019 Essentials";'Key'="WVDHN-86M7X-466P6-VHXV7-YY726" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2016 Datacenter";'Key'="CB7KF-BWN84-R7R2Y-793K2-8XDDG" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2016 Standard";'Key'="WC2BQ-8NRM3-FDDYY-2BFGV-KHKQY" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2016 Essentials";'Key'="JCKRF-N37P4-C2D82-9YXRT-4M63B" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2012 R2 Standard";'Key'="D2N9P-3P6X9-2R39C-7RTCD-MDVJX" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2012 R2 Datacenter";'Key'="W3GGN-FT8W3-Y4M27-J84CP-Q3VJ9" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2012 R2 Essentials";'Key'="KNC87-3J2TX-XB4WP-VCPJV-M4FWM" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2008 R2 Standard";'Key'="YC6KT-GKW9T-YTKYR-T4X34-R7VHC" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2008 R2 Enterprise";'Key'="489J6-VHDMP-X63PK-3K798-CPX3Y" })
 $kmsKeys += New-Object –TypeName PSObject –Prop ([ordered]@{'OS'="Microsoft Windows Server 2008 R2 Datacenter";'Key'="74YFP-3QFB3-KQT8W-PMXWJ-7M648" })

# Set KMS Key
$SetKeyOutPut = cscript c:\windows\system32\slmgr.vbs /ipk $kmsKeys[$kmsKeys.os.IndexOf($OS)].key
$SetKeyOutClean = $SetKeyOutPut | select -last 2 | select -First 1

if ($SetKeyOutClean.Contains("successfully")) { Write-host -ForegroundColor Green "Set key succesfully"}
Else { Write-host -ForegroundColor Yellow $SetKeyOutClean ; break }

# Activate KMS 
$ActivateOutPut = cscript c:\windows\system32\slmgr.vbs /ato
$ActivateOutClean = $ActivateOutPut | select -last 2 | select -First 1

if ($ActivateOutClean.Contains("successfully")) { Write-host -ForegroundColor Green "Activated succesfully"}
Else { Write-host -ForegroundColor Yellow $ActivateOutClean ; break }




Connect Powershell to Exchange Online

Check for connection, if not, then Establish connection

# Check for connection
$NotConnected = $true
$RMsessions = Get-PSSession
Foreach ($RMsession in $RMsessions) {
if ($RMsession.Computername -like "*outlook*") { $NotConnected = $false }
}

# Establish connection
if ($NotConnected ) {
$LiveCred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session 
cls
}