Skip to content

Latest commit

Β 

History

11 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Azure & Kubernetes (AKS) PowerShell Automation Scripts

PowerShell 5.1+ Azure CLI Kubernetes License: MIT

An enterprise-grade collection of PowerShell scripts designed for system administrators, DevOps engineers, and cloud architects to manage, monitor, troubleshoot, and automate Microsoft Azure services and Azure Kubernetes Service (AKS) clusters.


πŸ“‹ Table of Contents


πŸ“Œ Repository Overview

This repository provides reusable, modular PowerShell automation scripts for Azure infrastructure management. Every script includes:

  • Standard Comment-Based Help (.SYNOPSIS, .DESCRIPTION, .NOTES).
  • Explicit #Requires statements declaring dependent PowerShell modules.
  • Robust error handling and interactive menu prompts.
  • Clean output formatting (Console tables, GUI Out-GridView, HTML Mermaid flowcharts, CSV exports).

βš™οΈ Prerequisites & Requirements

PowerShell Version

  • PowerShell 5.1+ (Windows PowerShell) or PowerShell 7.x+ (PowerShell Core).

Required PowerShell Modules

Install the necessary Azure modules from the PowerShell Gallery:

# Install Azure Az module collection
Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force

# Install Azure Active Directory module (for AD Group management)
Install-Module -Name AzureAD -Scope CurrentUser -Repository PSGallery -Force

# Install SQL Server module (for Invoke-Sqlcmd queries)
Install-Module -Name SqlServer -Scope CurrentUser -Repository PSGallery -Force

External Command-Line Tools

Ensure the following CLI utilities are installed and available in your system environment PATH:

Tool Purpose Download Link
Azure CLI (az) Azure authentication and resource commands Install Azure CLI
kubectl Kubernetes cluster administration Install kubectl
kubelogin Azure AD token authentication for AKS Install kubelogin
OpenSSL PKI self-signed certificate hierarchy generation Download OpenSSL

πŸ“‚ Directory Structure

Powershell-Scripts/
β”œβ”€β”€ AKS/                        # Azure Kubernetes Service & Container Scripts
β”‚   β”œβ”€β”€ AKS Credential Download.ps1
β”‚   β”œβ”€β”€ AKS-Connect-v1.ps1
β”‚   β”œβ”€β”€ AKS-Istio-TrafficFlowCheck.ps1
β”‚   β”œβ”€β”€ AKS_connect.ps1
β”‚   β”œβ”€β”€ AKS_Node_Pool_Migration.ps1
β”‚   β”œβ”€β”€ GetPodLogs.ps1
β”‚   β”œβ”€β”€ Keda-Config-Validation.ps1
β”‚   └── PodTroubleshoot.ps1
β”œβ”€β”€ Azure/                      # Azure Cloud Infrastructure Administration Scripts
β”‚   β”œβ”€β”€ AD-Group-Owner addition.ps1
β”‚   β”œβ”€β”€ AFD-Flowchart.ps1
β”‚   β”œβ”€β”€ AppGateway-Flowchart.ps1
β”‚   β”œβ”€β”€ Application URL Response Monitor.ps1
β”‚   β”œβ”€β”€ Archive DB Index rebuild with Auto Resize.ps1
β”‚   β”œβ”€β”€ AVD Auto-Restart VM.ps1
β”‚   β”œβ”€β”€ AVD VM Autoshutdown.ps1
β”‚   β”œβ”€β”€ DB Query Run.ps1
β”‚   β”œβ”€β”€ DB_Details_Check.ps1
β”‚   β”œβ”€β”€ DB_Used space check-v1.ps1
β”‚   β”œβ”€β”€ List Resource without tags.ps1
β”‚   β”œβ”€β”€ SelfCert-Creation-Existing Root.ps1
β”‚   β”œβ”€β”€ SelfSignedCert_creation.ps1
β”‚   β”œβ”€β”€ Specific RG SQL Server DB_DTU Size List.ps1
β”‚   β”œβ”€β”€ SQL-Connection-Monitor.ps1
β”‚   β”œβ”€β”€ Tag-Copy to RG.ps1
β”‚   β”œβ”€β”€ TAG-Update ALL Resources.ps1
β”‚   β”œβ”€β”€ Tag-Value-View-ALLRG.ps1
β”‚   β”œβ”€β”€ User Access Removal.ps1
β”‚   └── VM-AutoShutdown.ps1
β”œβ”€β”€ LICENSE                     # MIT Open-Source License
└── README.md                   # Repository Documentation

πŸ› οΈ Script Catalog

1. Azure Kubernetes Service (AKS) & Container Management (AKS/)

Script File Synopsis / Functionality
AKS Credential Download.ps1 Queries active Azure CLI subscription for all deployed AKS clusters and batch-downloads/merges cluster access credentials into local ~/.kube/config.
AKS-Connect-v1.ps1 Interactive CLI to download AKS cluster credentials into separate environment files (Non-prod/Prod), switch cluster contexts, select namespaces, and convert Azure AD tokens via kubelogin.
AKS-Istio-TrafficFlowCheck.ps1 Interactive traffic tracer for Istio mesh VirtualServices. Maps route paths, target Services, resolves pod selectors, and outputs an ASCII topology map.
AKS_connect.ps1 Scans ~/.kube/ for config files, updates $env:KUBECONFIG, prompts for context and default namespace selection, and executes kubelogin conversion.
AKS_Node_Pool_Migration.ps1 Automates workload migration between AKS node pools: creates new node pool, cordons old nodes, drains active pods via kubectl drain, verifies pod status, and deletes old node pool.
GetPodLogs.ps1 Interactive log fetcher and parser. Fetches pod logs live via kubectl or reads disk files, parses Java/Spring/K8s entries, extracts metadata (User/Task IDs), and filters by log level or keywords.
Keda-Config-Validation.ps1 Diagnostic suite validating AKS KEDA add-on, OIDC issuer, Workload Identity, ServiceAccount annotations, federated credentials, Prometheus ScaledObjects, and Azure RBAC role assignments.
PodTroubleshoot.ps1 Interactive pod troubleshooting wizard. Filters Ready/Not-Ready pods, parses container limits, requests, environment variables, mounts, lifecycle events, and suggests kubectl diagnostic commands.

2. Azure Virtual Desktop (AVD) & VM Operations (Azure/)

Script File Synopsis / Functionality
AVD Auto-Restart VM.ps1 Scheduled maintenance workflow for AVD Host Pools: enables drain mode, notifies active users with pop-up messages to save work, waits for grace period, restarts session host VMs, and re-enables logins.
AVD VM Autoshutdown.ps1 Azure Function App timer script that evaluates session host connections in AVD host pools and automatically stops idle VMs with zero active connections.
VM-AutoShutdown.ps1 Checks logged-in user sessions on Azure VMs via WinRM / PSRemoting (quser), fetches admin credentials from Key Vault, and executes async deallocate/shutdown (Stop-AzVM -NoWait) for idle VMs.

3. Traffic Routing & Flowchart Visualization (Azure/)

Script File Synopsis / Functionality
AFD-Flowchart.ps1 Interactively prompts for Azure Front Door profile, Endpoint, and Route, maps custom domains, SSL certificates, WAF rule sets, origin groups, and origins, exporting an interactive HTML flowchart powered by Mermaid.js.
AppGateway-Flowchart.ps1 Traces Azure Application Gateway routing topology (Listeners, URL path maps, path rules, HTTP settings, backend pools, backend targets) and generates a visual Mermaid.js HTML diagram opened in default browser.

4. Azure SQL Database Administration & Sizing (Azure/)

Script File Synopsis / Functionality
Archive DB Index rebuild with Auto Resize.ps1 Dynamically scales Azure SQL Database DTU tiers up (e.g. S2 -> S3), executes parallel index maintenance stored procedures (Invoke-Sqlcmd), monitors completion, and restores databases to original DTU size.
DB Query Run.ps1 Interactively executes SQL queries across multiple Azure SQL Servers and databases using GUI selection (Out-GridView) via Azure AD Access Tokens or Key Vault secrets.
DB_Details_Check.ps1 Enumerates Azure SQL Servers, presents a selection menu, evaluates database compute models (DTU / Serverless / Provisioned vCore), editions, SKUs, max size, and backup redundancy into a clean table.
DB_Used space check-v1.ps1 Queries Azure Monitor metrics (storage & storage_percent) to calculate used space in GB vs max allocated size, geo-replication status, and DTU sizes for databases across subscriptions.
Specific RG SQL Server DB_DTU Size List.ps1 Lists all Azure SQL Databases within a specific Resource Group & Server along with max size in GB, edition, and requested/current DTU or vCore service objectives.
SQL-Connection-Monitor.ps1 Periodically polls active sessions against sys.sysprocesses on an Azure SQL database via ADO.NET (SqlConnection), summarizing session counts per host and logging timestamped rows to a CSV file.

5. Security, PKI & Access Control (Azure/)

Script File Synopsis / Functionality
AD-Group-Owner addition.ps1 Prompts for user UPNs, iterates through target Azure Active Directory group display names, checks current ownership, and adds missing users as group owners via the AzureAD module.
User Access Removal.ps1 Resolves Azure AD Object ID for a user email (UPN), iterates through role assignments across Key Vault, AKS, Resource Group, and Subscription scopes, and removes assignments via Remove-AzRoleAssignment.
SelfSignedCert_creation.ps1 Generates a complete 3-tier self-signed PKI hierarchy via OpenSSL: Root CA (10-year), Intermediate CA (10-year), and Server Cert with Subject Alternative Names (SANs), exported as a PFX bundle.
SelfCert-Creation-Existing Root.ps1 Generates an OpenSSL server configuration file with SANs, creates CSR, signs the certificate using an existing Intermediate CA cert/key, and exports a password-protected PFX file for IIS.

6. Resource Tagging & Management (Azure/)

Script File Synopsis / Functionality
List Resource without tags.ps1 Scans an Azure Resource Group via Get-AzResource and lists all child resources missing tags.
TAG-Update ALL Resources.ps1 Propagates missing tags defined at the Resource Group level to all child resources inside that RG, respecting an exclusion list.
Tag-Copy to RG.ps1 Copies and merges resource tags from a source Resource Group to a destination Resource Group using Set-AzResourceGroup.
Tag-Value-View-ALLRG.ps1 Scans all Resource Groups in a subscription, consolidates unique tag keys/values into a matrix table, displays GUI grid (Out-GridView), and exports results to CSV.
Application URL Response Monitor.ps1 Periodically sends HTTP requests via Invoke-WebRequest to a target URL, logs status codes, handles exceptions, and records timestamped entries to a text file.

πŸš€ Usage Examples

1. Authenticate to Azure CLI and Azure PowerShell

# Authenticate Azure CLI
az login

# Authenticate Azure PowerShell module
Connect-AzAccount

2. Download All AKS Cluster Credentials

.\AKS\"AKS Credential Download.ps1"

3. Run Pod Troubleshooting Wizard

.\AKS\PodTroubleshoot.ps1

4. Generate Application Gateway Traffic Flowchart

.\Azure\AppGateway-Flowchart.ps1 -SubscriptionId "00000000-0000-0000-0000-000000000000"

5. Parse and Filter Pod Logs Live

.\AKS\GetPodLogs.ps1 -PodName "my-app-pod-xyz" -Namespace "prod" -AddKubectlTimestamps

πŸ“– Built-In Help & AST Verification

All scripts fully support standard PowerShell comment-based help. You can inspect detailed parameters and usage notes directly in your terminal:

# View synopsis and parameter details for any script
Get-Help .\AKS\Keda-Config-Validation.ps1 -Full
Get-Help .\Azure\AVD Auto-Restart VM.ps1 -Detailed

AST Syntax Verification Test

You can run a one-line PowerShell test to verify that every .ps1 file in the repository passes Abstract Syntax Tree parsing without errors:

Get-ChildItem -Path . -Filter *.ps1 -Recurse | ForEach-Object {
    $err = @()
    $null = [System.Management.Automation.Language.Parser]::ParseFile($_.FullName, [ref]$null, [ref]$err)
    if ($err.Count -gt 0) {
        Write-Host "FAIL: $($_.Name) - $($err[0].Message)" -ForegroundColor Red
    } else {
        Write-Host "PASS: $($_.Name)" -ForegroundColor Green
    }
}

🀝 Contributing

Contributions, issues, and feature requests are welcome!

  1. Fork the repository.
  2. Create a feature branch (git checkout -b feature/AmazingFeature).
  3. Ensure all .ps1 files pass AST syntax checks and include comment-based help headers.
  4. Commit your changes (git commit -m 'Add new Azure automation script').
  5. Push to the branch (git push origin feature/AmazingFeature).
  6. Open a Pull Request.

πŸ“œ License

Distributed under the MIT License. See LICENSE for more information.

About

Enterprise-grade PowerShell automation scripts for managing, troubleshooting, and administering Azure cloud infrastructure and Azure Kubernetes Service (AKS) clusters.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages