Phillip fyhn Phillip fyhn - 3 months ago 10
PowerShell Question

Loading script depending on userinput

Hi im fairly new to the whole scripting scene and was hoping somebody could help me. I've created a menu which depending on user input will prompt an answer back, but i need to make it so if you press "1" it will load another script into this script and so on
my current code is this :

function Show-Menu
{
param (
[string]$Title = 'Menu'
)
cls
Write-Host " $Title "

Write-Host "1: Tast '1' for at oprette OU"
Write-Host "2: Tast '2' For at oprette grupper"
Write-Host "3: Tast '3' For at importere brugere i grupper"
Write-Host "4: Tast '4' For at eksportere brugerlister til CSV"
Write-Host "5: Tast '5' For at slette brugere"
Write-Host "6: Tast '6' For at ændre password"
Write-Host "Q: Tast 'X' For at afslutte."
}
do
{
Show-Menu
$input = Read-Host "Please make a selection"
switch ($input)
{
'1' {
cls
'Du valgte Nummer #1'
} '2' {
cls
'Du valgte Nummer #2'
} '3' {
cls
'Du valgte Nummer #3'
} '4' {
cls
'Du valgte Nummer #4'
} '5' {
cls
'Du valgte Nummer #5'
} '6' {
cls
'Du valgte Nummer #6'

} 'q' {
cls
'Afslutter nu'
return
}
}
pause
}
until ($input -eq 'q')


any tips on how to load scripts into this script is appreciated


  • Phillip


Answer

First up, don't use input as a variable name - $input is an automatic variable and you may end up seeing some weird and unexpected behavior by attempting to overwrite it.

For "loading" scripts, use the dot-sourcing method, as follows:

. C:\path\to\script.ps1

The above will execute script.ps1 in the calling scope, so all variable and function definitions in the script is available afterwords:

do
{
     Show-Menu
     $choice = Read-Host "Please make a selection"
     switch ($choice)
     {
        '1' {
            cls
            'Du valgte Nummer #1'
            . C:\path\to\script1.ps1
        } 
        '2' {
            cls
            'Du valgte Nummer #2'
            . C:\path\to\script2.ps1
        } 
        '3' {
            cls
            'Du valgte Nummer #3'
            . C:\path\to\script3.ps1
        } 
        # og så videre ...
        } 
        'q' {
            cls
            'Afslutter nu'
                return
        }
     }
     pause
}
until ($choice -eq 'q')

Finally, you may want to go for either only Danish or only English text in the output, but that's more of a pet peeve on my part :-)