PowerShell Parameters provide an excellent and easy way to make the script more dynamic and flexible for the users and the owner’s needs by allowing the script to take action based on the passed value. This makes the script shorter and much easier for updates and bug fixes. If you never wrote a PowerShell parameter, then no worry as this series takes you on a journey from zero to hero in PowerShell parameters.

We start with a basic PowerShell script and step by step add more features, PowerShell Functions, and PowerShell parameters. When you finish reading this post, you will have a clear understanding of the PowerShell parameters, how to write them, and some best practices.

Prerequisites

You can use Windows PowerShell ISE to follow, but I highly recommend using PowerShell 7 with VSCode. PowerShell 7 and VSCode are free to download plus they work with most OS including Linux and macOS

What basic PowerShell script looks like?

Before start explaining what is PowerShell parameters, let’s see and start with a regular basic PowerShell script and use it as a starting point so that later on we learn how to make the PowerShell script more flexible by using PowerShell Parameters and PowerShell Functions.

The following PowerShell script gets the number of items in a folder called Directory1, then copies the content from Directory1 to Directory2. After that, it gets the number of content in Directory2 and displays the count on the screen.

let’s name this script as PSCopy.ps1

#Get Number of Files in the source folder
$NumberOfSourceFiles=Get-ChildItem -Path C:\Directory1 -Recurse
Write-Host "The Number of files in C:\Directory1 : " -NoNewline
Write-Host  $($NumberOfSourceFiles.count) -ForegroundColor Green
#Copy items to Destination folder
$NumberOfSourceFiles | Copy-Item -Destination "C:\Directory2" -Force 
#Get Number of file in the destination folder
$NumberOfDestFiles=Get-ChildItem -Path C:\Directory2 -Recurse
Write-Host "The Number of files in C:\Directory2 : " -NoNewline
Write-Host  $($NumberOfDestFiles.count) -ForegroundColor Green

Save the PowerShell script and then start it. When the script starts, the output of this script looks like this.

Script Output
Script Output

All looks fine, the PowerShell script did what it should do. But did you notice the number of hard-coded values that are represented by the directory paths C:\Directory1 and C:\Directory2 and the number of times these values are repeated?!

Changing the directory’s paths or structure takes a long time, and also it’s possible to forget to update some values inside the script. So let’s start learning the basics required to utilize PowerShell parameters.

Defining PowerShell Parameters

To make this script more flexible for the user, the users should be able to specify the source and destination folder without having to edit the PowerShell Script and change these values manually.

To create a PowerShell parameter we use the Param keyword. The Param block is defined by using opening and closing parentheses (). When typing the Param, make sure it’s written at the top of the PowerShell script. Let’s see it in action.

The PowerShell parameter name can be whatever you want prepended with a $, it’s actually a variable, same way.

In the following example, a parameter named FirstParameter is defined.

Param( # Param keywork on the top followed by an opened parentheses
$FirstParameter  #<---------- This is the Parameter
) #The end of Param block

#The rest of the code
Write-Host "The user Typed: $($FirstParameter)"

Save the script and give it whatever name you like, I used 1stparam.ps1. Executing this script like the following

PS C:\> .\1stparam.ps1 -FirstParameter "Param1"

Here is how the output looks like

The user Typed: Param1

Follow these steps to write your first PowerShell parameter:

  • The code block started with the word Param and then an open parentheses
  • Write the parameter name as a variable.
  • Close the parentheses
How PowerShell Read and passes the parameter (Basic view)

So in the example above, the user passes Param1 for the FirstParameter parameter. PowerShell assigns Param1 to FirstParameter and shows the result.

When calling PowerShell parameter using any IDE, a list will popup with the available parameters after typing the cmdlet name followed by space. But when using the PowerShell console, you can use the CTRL+Space bar after typing the - to list the available parameters.

Showing PowerShell Parameters

Defining More Than One PowerShell Parameter

There is a small trick you need to watch for. If you have more than one parameter, you need to add a comma , at the end of each parameter name except the last one. But if you have only one parameter no need to add any comma at the end of the parameter name.

Check the previous 1stParam.ps1 example and see how the PowerShell parameter decleared, there was no comma at the end of the parameter name.

Let’s have another example and add an additional two parameters.

Param( # Param keywork on the top followed by an opened parentheses
$FirstParameter,  
$SecondParameter, #All the parameter must have comma "," at the end of the parameter name
$ThirdParameter  # Except the last parameter there is no comma "," at the end
)#The end of Param scope

#The rest of the code
Write-Host "First Parameter value: $($FirstParameter)" 
Write-Host "Second Parameter value: $($FirstParameter)"
Write-Host "Third Parameter value: $($FirstParameter)" 

As you can see all the parameters ends with a comma “,” except the last one. So FirstParameter and SecondParameter have comma “,” at the end of the parameter name, but the ThirdParameter doesn’t. The same applies if you have two or more parameters.

PowerShell Parameter best practices – Part 1

For now, try to follow these points as the best practices:

  • Use a meaningful full parameter name. for example, use ComputerName instead of PC, or CN or even Computer. Keep your parameter readable and give the user the ability to understand what they need to type.
  • Don’t use a very long parameter name. for example, don’t use TypeHereTheComputerNameForYourMachine

More tips and best practices are on the way.

Using PowerShell Parameter inside PowerShell Function

PowerShell Function Basics

Think of a PowerShell script that needs to do a similar task multiple times during the runtime, such as showing an error message on the screen with some details. There are two possible ways. You can write the same code multiple times as required or simply use the PowerShell function to wrap the block of code, give it a name, and call it when required.

Functions make the code shorter, prevent repetitive code, and keep the code easier to understand and update.

PowerShell function starts with the word Function then the name of the function, which can be whatever you want, and a block of code in an opening and closing curly brackets { }.

Yes you can use any name for the Function, but its recommend to use the approved verbs as listed in Microsoft so instead of naming a function Display-ErrorMessage, make it Show-ErrorMessage

We will go through the basics of function and how to add PowerShell parameters to it. PowerShell function looks like this

Function NameOfFunction {
#Block of Code
}

Don’t get confused between the parameter and function brackets, the Param uses parentheses ( ) but the function uses curly brackets { }

In the next example, PowerShell count from 0 to 10, and with each number, PowerShell executes the Show-MyMessage code block, which is the function.

Function Show-MyMessage {
    Write-Host "Inside Function Code Started at " -NoNewLine
    Get-Date
    }
for ($i = 0; $i -lt 10; $i++) {
    Write-Host "My counting is $($i)"
    Show-MyMessage
    Write-Host "Remaining code inside the script"
}
PS C:\> My counting is 0
Inside Function Code Started at
Tuesday, May 10, 2022 9:50:23 AM
Remaining code inside the script
My counting is 1
Inside Function Code Started at Tuesday, May 10, 2022 9:50:23 AM
Remaining code inside the script
My counting is 2
Inside Function Code Started at Tuesday, May 10, 2022 9:50:23 AM
Remaining code inside the script
My counting is 3
Inside Function Code Started at Tuesday, May 10, 2022 9:50:23 AM
Remaining code inside the script
My counting is 4
Inside Function Code Started at Tuesday, May 10, 2022 9:50:23 AM
Remaining code inside the script
My counting is 5
Inside Function Code Started at Tuesday, May 10, 2022 9:50:23 AM
Remaining code inside the script
My counting is 6
Inside Function Code Started at Tuesday, May 10, 2022 9:50:23 AM
Remaining code inside the script
My counting is 7
Inside Function Code Started at Tuesday, May 10, 2022 9:50:23 AM
Remaining code inside the script
My counting is 8
Inside Function Code Started at Tuesday, May 10, 2022 9:50:23 AM
Remaining code inside the script
My counting is 9
Inside Function Code Started at Tuesday, May 10, 2022 9:50:23 AM
Remaining code inside the script
Code Execution order

Adding Parameter to the function

PowerShell functions do not only make the code shorter and easier to update as mentioned before, but they are also flexible and accept parameters.

When adding parameters to the function, the function is called from inside the script using the same method of calling a parameter by using the - symbol and providing the parameter name and its value.

To start, use the parameter keyword Param() inside the function. The Param() keyword is placed just below the function word.

In the previous example, Show-MyMessage.ps1, the Show-MyMessage function output “Inside Function Code Started at“. Let’s update it so a customized message is displayed in the output. This customized message is passed from the script block to the function as a parameter.

Function Show-MyMessage{ # <------ Function Start here
Param ( # <---------- Parameter start here 
$NewMessage # <----- Parameter Name
) # <---- End of Parameter Block
### the remainding Code of the function block
} # <------ Function Closure

Show-MyMessage #Call the Function name to execute the Function code block.
# Rest of PowerShell script.
Function Show-MyMessage { # <--- Function start
    Param ( # <--- Parameter Start
     $Message # <--- Parameter name
    ) # <--- Parameter block finish
    Write-Host "Function Block Started" -ForegroundColor Yellow
    Write-Host $Message # <--- The value of $Message is from the script block line 12
    Get-Date
    } # <--- Function finished

for ($i = 0; $i -lt 10; $i++) {
    Write-Host "Script Block $($i)" -ForegroundColor Blue
    Show-MyMessage -Message "Debug For $($i) "
}

The output of the script, and see how we manage to pass the text “Debug For $($i)” to the function and the function parameter.

Result of updated Show-MyMessage.ps1

PowerShell called the Show-MyMessage.ps1 function with its parameter -Message and passes the value.

Summary

With this quick part one of this series, you learn how to declare PowerShell parameters for your script and function. There is still a lot to come. In the next post, I will explain how to make the PowerShell parameter mandatory and some other basics.

5/5 - (1 vote)