top of page

PowerShell Parameters (Basic)

  • Writer: Damian Scoles
    Damian Scoles
  • Jun 25, 2019
  • 2 min read



Why use external arguments for PowerShell scripts? External parameters allow for options to be selected that correspond to functions or actions within the script. For example, if you wanted to trigger a HTML report for output, maybe we would specify a parameter of 'Report' .


Example 1


Run from PowerShell:


Get-ExchangeHealth.ps1 Office365


By running this


$Switch1 = $args[0]


Later in the script we can then use the parameter to make a choice:


If (Switch1 -ne 'Office365) {

(Get-ExchangeServer).Name

} Else {

Write-Verbose 'Connected to Exchange Online, no Exchange Servers to query'

}


Example 2


Run from PowerShell:


Get-ExchangeHealth.ps1 Office365 MailboxStats


Now not only do we get to connect to Office 365, but we can also query mailbox stats in the same run.


Code in the script:


param(

[ Parameter(Mandatory=$false,ParameterSetName="Office365")]

[switch]$Office365,

[Parameter(Mandatory=$false,ParameterSetName="MailboxStats")]

[switch]$MailboxStats

)


Later in the script we would have two code blocks to handle these requests:


(not a complete sample)


If ($Environment -eq 'Office365') {

Write-host ' '

Write-host ' *** ' -ForegroundColor White -NoNewline

Write-host 'Script will examine Exchange Online now.' -ForegroundColor Red -NoNewline

Write-host ' *** ' -ForegroundColor White

Write-host ' '

$ExOMenu = {

Write-Host " ***********************************" -ForegroundColor White

Write-Host " Exchange Online Health Check Menu" -ForegroundColor Cyan

Write-Host " ***********************************" -ForegroundColor White


… and so on… Then, code for the mailbox stats options:


I f ($MailboxStats) {

Get-mailbox | Get-MailboxStatistics | select-object DisplayName, {$_.TotalItemSize.Value.ToMB()}

}


Example 3


Run from PowerShell:


Get-ExchangeHealth.Ps1 SecurityComplianceCenter


Then we have this code in the script to look for this switch:


$SCC = $args[0]


Then later in the script, we can check to see if the parameter populated this variable and if so, execute some code (sample below):


If ($SCC) {

$LiveCred = Get-Credential

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $LiveCred -Authentication Basic -AllowRedirection

Import-PSSession $Session

Get-RetentionComplianceTag

}


Thus we can use parameters to have our script handle additional tasks when executing. The above examples are simplistic, but do provide an introductory view into how they can be utilized.

 
 
 

Recent Posts

See All
Null. Empty. Space? How to Detect?

** Disclaimer ** I do not know everything about PowerShell and I am sure I will miss some methods of detection of empty values. However,...

 
 
 

Comments


© 2016-2020 by Damian Scoles and Dave Stork.

bottom of page