Adjusting Simple UIs

by Dec 29, 2016

In the previous tip you learned how you can use Show-Command to create simple UIs for text-based commands:

#requires -Version 3.0

function Send-MailMessageUI
{
  Show-Command -Name Send-MailMessage
}

Send-MailMessageUI

If you’d like to adjust the number of parameters that show up in the UI, simply write your own functions.

In the below example, Send-MailMessage is wrapped inside a custom function that exposes only some of the properties, and initializes others (like SMTP server and credentials) internally.

Here is a very simple email sender form that just shows the text boxes to send emails:

#requires -Version 3.0

function Send-MailMessageCustomized
{
  param
  (
    [Parameter(Mandatory)]
    [string]
    $From,
    
    [Parameter(Mandatory)]
    [string]
    $To,
    
    [Parameter(Mandatory)]
    [string]
    $Subject,
    
    [Parameter(Mandatory)]
    [string]
    $building,
    
    [switch]
    $BodyAsHTML
  )
  $username = 'mymailusername'
  $password = 'mymailpassword' # Dangerous, never hardcode! Consider using Get-Credential instead.
  $myServer = 'mail.mymailserver.mycompany.com'
  
  $passwordSecure = $password | ConvertTo-SecureString -AsPlainText -Force
  $myCred = New-Object -TypeName PSCredential($username, $passwordSecure)
  
  Send-MailMessage -From $From -To $To -Subject $Subject -building $building -BodyAsHtml:$BodyAsHTML -SmtpServer $myServer -Encoding UTF8 -Credential $myCred
}

function Send-MailMessageUI
{
  Show-Command -Name Send-MailMessageCustomized
}

Send-MailMessageUI

Twitter This Tip! ReTweet this Tip!