Link to home
Start Free TrialLog in
Avatar of Christian Hans
Christian HansFlag for United States of America

asked on

Help building a Powershell Menu with options

How would I create an interactive menu when opening ISE?

I've created a new ISE profile under C:\Users\heyitsme\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

I am basically wanting to get prompted for 3 options...

Option 1 - Connect to Exchange Online  (which points to another PS1 file that contains the Exchange Online connection info c:\scripts\ExOL.ps1)
Option 2 - Connect to Exchange On-Prem  (which points to another PS1 file that contains the Exchange On-Prem connection info c:\scripts\ExOP.ps1)
Option 3 - Quit

Does anyone have any pointers on how to set something like this up?

Im trying to put together a bunch of things but am not having any luck...
Example: https://www.petri.com/building-a-powershell-console-menu-revisited-part-1
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

$menu = @'
1 Show Info About a Computer
2 Connect to Azure
3 Connect to Office 365
Q Quit

Select a task by number or Q to Quit

'@
Write-Host "My Menu" -ForegroundColor Cyan
$r = Read-host $menu


Switch ($r) {
"1" {
    Write-Host "Getting system information" -ForegroundColor Green
    start-process msinfo32.exe
}
 
"2" {
    Write-Host "Connect to Azure" -ForegroundColor Green
    .\Connect-Azure.ps1
}
 
"3" {
    Write-Host "Connect to Office 365" -ForegroundColor Green
    .\connect-office365.ps1
}
 
"Q" {
    Write-Host "Quitting" -ForegroundColor Green
}
 
default {
    Write-Host "I don't understand what you want to do." -ForegroundColor Yellow
 }
} #end switch

Open in new window

connect-office365.ps1
function connect-service 
{
  <#
      .SYNOPSIS
      Describe purpose of "connect-service" in 1-2 sentences.

      .DESCRIPTION
      Add a more complete description of what the function does.

      .EXAMPLE
      connect-service
      Describe what this call does

      .NOTES
      Place additional notes here.

      .LINK
      URLs to related sites
      The first link is opened by Get-Help -Online connect-service

      .INPUTS
      List of input types that are accepted by this function.

      .OUTPUTS
      List of output types produced by this function.
  #>


  $securepassword = ConvertTo-SecureString -String 'yourpassword' -AsPlainText -Force
  $credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ('youraccount@example.com', $securepassword)
  #$credential = Get-Credential
  Import-Module -Name MsOnline  -Force
  Connect-MsolService -Credential $credential
  Import-Module -Name Microsoft.Online.SharePoint.PowerShell -DisableNameChecking -Force
  Connect-SPOService -Url https://techsupport4me-admin.sharepoint.com -credential $credential
  Import-Module -Name LyncOnlineConnector -Force
  $sfboSession = New-CsOnlineSession -Credential $credential
  Import-PSSession -Session $sfboSession -AllowClobber
  $exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.protection.outlook.com/powershell-liveid/ -Credential $credential -Authentication Basic -AllowRedirection
  Import-PSSession -Session $exchangeSession -DisableNameChecking -AllowClobber
  $ccSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $credential -Authentication Basic -AllowRedirection

  $Skypesession = New-CsOnlineSession -Credential $credential -Verbose

  Import-PSSession -Session $ccSession -Prefix cc -AllowClobber
  Write-Host ("$sfboSession = Sharepoint Session")
  Write-Host ("$exchangeSession = Exchange Session")
  Write-Host ("$ccSession = Compliance Session")
  Write-Host ("$Skypesession = Skype Session")
}
function disconnect-service 
{
  <#
      .SYNOPSIS
      Describe purpose of "disconnect-service" in 1-2 sentences.

      .DESCRIPTION
      Add a more complete description of what the function does.

      .EXAMPLE
      disconnect-service
      Describe what this call does

      .NOTES
      Place additional notes here.

      .LINK
      URLs to related sites
      The first link is opened by Get-Help -Online disconnect-service

      .INPUTS
      List of input types that are accepted by this function.

      .OUTPUTS
      List of output types produced by this function.
  #>


  Remove-PSSession -Id $sfboSession  
  Remove-PSSession -Id $exchangeSession 
  
  try
  {
    Remove-PSSession -Id $ccSession
  }
  # NOTE: When you use a SPECIFIC catch block, exceptions thrown by -ErrorAction Stop MAY LACK
  # some InvocationInfo details such as ScriptLineNumber.
  # REMEDY: If that affects you, remove the SPECIFIC exception type [System.Management.Automation.ValidationMetadataException] in the code below
  # and use ONE generic catch block instead. Such a catch block then handles ALL error types, so you would need to
  # add the logic to handle different error types differently by yourself.
  catch [Management.Automation.ValidationMetadataException]
  {
    # get error record
    [Management.Automation.ErrorRecord]$e = $_

    # retrieve information about runtime error
    $info = New-Object -TypeName PSObject -Property @{
      Exception = $e.Exception.Message
      Reason    = $e.CategoryInfo.Reason
      Target    = $e.CategoryInfo.TargetName
      Script    = $e.InvocationInfo.ScriptName
      Line      = $e.InvocationInfo.ScriptLineNumber
      Column    = $e.InvocationInfo.OffsetInLine
    }
    
    # output information. Post-process collected info, and log info (optional)
    $info
  }
 
  Disconnect-SPOService
}

<#
    .Synopsis
    Connect-Office365
    .DESCRIPTION
    Connects Session to Office 365
    .EXAMPLE
    connect-office365 -connection connect
    .EXAMPLE
    connect-office365 -connection disconnect
    .INPUTS
    None
    .OUTPUTS
    None
    .NOTES
    General notes
    .COMPONENT
    The component this cmdlet belongs to
    .ROLE
    The role this cmdlet belongs to
    .FUNCTIONALITY
    The functionality that best describes this cmdlet
#>
function Connect-O365
{
  <#
      .SYNOPSIS
      Describe purpose of "Connect-O365" in 1-2 sentences.

      .DESCRIPTION
      Add a more complete description of what the function does.

      .PARAMETER Connection
      Describe parameter -Connection.

      .EXAMPLE
      Connect-O365 -Connection Value
      Describe what this call does

      .NOTES
      Place additional notes here.

      .LINK
      URLs to related sites
      The first link is opened by Get-Help -Online Connect-O365

      .INPUTS
      List of input types that are accepted by this function.

      .OUTPUTS
      List of output types produced by this function.
  #>


     
  Param (
    [Parameter(Mandatory = $true,HelpMessage = 'Valid options: Connect or Disconnect',Position = 1)]            
    [ValidateNotNull()]
    [ValidateNotNullOrEmpty()]
    [ValidateSet('Connect', 'Disconnect')] 
    [string]$Connection
  )
  if ($Connection -eq 'Connect')
  {
    Write-Host  'Connecting to Office 365 session'
    Write-Host  'Do NOT close this Window while session active'
    connect-service
  }
  else 
  { 
    Write-Host  'disconnecting from Office 365 Session'
    disconnect-service 
  }
}
Connect-O365 -Connection Connect

Open in new window


you will need the modules use install-module modulename
Here is something I was playing around with.  Perhaps this can help.  Can't remember where I got it from or whether or not I modified it:

 #Areyousure function. Allows user to select y or n when asked to exit. Y exits and N returns to main menu.  
 function areyousure {$areyousure = read-host "Are you sure you want to exit? (y/n)"  
           if ($areyousure -eq "y"){exit}  
           if ($areyousure -eq "n"){mainmenu}  
           else {write-host -foregroundcolor red "Invalid Selection"   
                 areyousure  
                }  
}  
 #Mainmenu function. Contains the screen output for the menu and waits for and handles user input.  
 
 function mainmenu{  
 cls  
 echo "---------------------------------------------------------"  
 echo ""  
 echo ""  
 echo "    1. Open Notepad"  
 echo "    2. Open Calculator"  
 echo "    3. Exit"  
 echo ""  
 echo ""  
 echo "---------------------------------------------------------"  
 $answer = read-host "Please Make a Selection"  
 if ($answer -eq 1){notepad}  
 elseif ($answer -eq 2){calc}  
 elseif ($answer -eq 3){areyousure}  
 else {write-host -ForegroundColor red "Invalid Selection"  
       sleep 5  
       mainmenu  
   }  
}
 mainmenu  

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Another approach would be to add entries to the Add-Ons menu structure so that you can simply select the external scripts to run from the menu.  This can be achieved by adding some code to the ISE profile:


function Add-ISEMenuItem([String]$MenuName,[String]$Name,[ScriptBlock]$Script,[String]$Shortcut) 
{
    try{
         if ( [String]::IsNullOrWhiteSpace($Shortcut ) )
         {
            $Menus[$MenuName].Submenus.Add($Name, $Script,$null) | Out-Null   
         }
         else 
         { 
            $Menus[$MenuName].Submenus.Add($Name, $Script, $Shortcut) | Out-Null 
         }
    }
    catch 
    {
        Write-Warning $PSItem
    }
}
Add-ISEMenuItem -MenuName "AddOns" -Name "Online Exchange" -Script { c:\scripts\ExOL.ps1 } -Shortcut 'Alt+Shift+L'
Add-ISEMenuItem -MenuName "AddOns" -Name "On prem Exchange" -Script { c:\scripts\ExOP.ps1 } -Shortcut 'Alt+Shift+P'

Open in new window


While the structure for adding menus implies that you can use multiple menus, you can only use the Add-Ons.