Search code examples
powershelluser-inputoptionmenu

Have user select file name from commandline option menu


I want a script that asks the user to select from a list option, like:

Please select a kind of report

1.HeadOffice 
2.All offices
3.Office1
4.Office2
5.Office3

Code:

$headoffice = headoffice.csv 
$Alloffices = alloffices.csv
$Office1 = office1.csv
$Office2 = office2.csv
$Office3 = office3.csv

$csv = "selected one"

Foreach($target in $csv){

    # Do custom scan AND rainbows.
}

Is this possible?


Solution

  • First, you should create a hashtable where the file names are numbered like so:

    $table = @{
        '1' = 'headoffice.csv'
        '2' = 'alloffices.csv'
        '3' = 'office1.csv'
        '4' = 'office2.csv'
        '5' = 'office3.csv'
    }
    

    Next, you can ask the user to select an option using Read-Host and a here-string:

    $choice = Read-Host @'
    Please select a kind of report
    
    1.HeadOffice 
    2.All offices
    3.Office1
    4.Office2
    5.Office3
    '@
    

    Finally, you can index the hashtable with that value and thereby access the appropriate file name:

    $filename = $table[$choice]
    

    Note that if you are working with CSV files, you might also want to read up on Import-Csv.