PowerShell Switch Statement with Examples


Switch statements in PowerShell are really useful to design a script with a menu, and to perform actions based on the selection.

Let's take a look at a few examples.

Example1 :

    <# 
    
    	PowerShell Switch Statement Example
    
    	Determine Day of the Week
    
    #>
    
    # User Input
    $number = Read-Host "Enter a number from 1 to 7"
    
    switch ($number) {
        1 {
            Write-Host "Day 1: Sunday"
        }
        2 {
            Write-Host "Day 2: Monday"
        }
        3 {
            Write-Host "Day 3: Tuesday"
        }
        4 {
            Write-Host "Day 4: Wednesday"
        }
        5 {
            Write-Host "Day 5: Thursday"
        }
        6 {
            Write-Host "Day 6: Friday"
        }
        7 {
            Write-Host "Day 7: Saturday"
        }
        default {
            Write-Host "Invalid number. Please enter a number from 1 to 7."
        }
    }
    

    Enter a number from 1 to 7: 3

    Day 3: Tuesday


Example 2:

    # Menu Options
    Write-Host "AI Operations Menu:"
    Write-Host "1. Stable Diffusion"
    Write-Host "2. AI Analysis"
    Write-Host "3. Exit"
    
    $choice = Read-Host "Enter Menu Option 1 - 3"
    
    $choice = [int]$choice
    
    switch ($choice) {
        1 {
            Write-Host "You selected: Stable Diffusion"
        }
        2 {
            Write-Host "You selected: AI Analysis"
        }
        3 {
            Write-Host "Exiting.."
        }
        default {
            Write-Host "Invalid choice. Please enter a valid option (1, 2, or 3)."
        }
    }
    

    Enter Menu Option 1 - 3: 2

    You selected: AI Analysis

PowerShell Switch Menu Example
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap