Advanced PowerShell Function Explained with Examples

Photo of author

By Victor Ashiedu

Published

Do you want to take your PowerShell scripting to the next level by building functions? Come with me on this ride as I teach you all you need to know about PowerShell Functions.

One of the most (if not the most) important elements of a function is learning how to define parameters. Although I will touch on this in this article if you want to learn about parameters, read my guide – PowerShell Param: Syntax, Types, Attributes, Arguments, And Examples

Overview

When you write a collection of PowerShell statements that has a name you can assign, you have a function.

When you create a function, you can then type the name of the function like a cmdlet and run it. So, when you run the function, PowerShell executes the statements in the function.

Earlier, I hinted that a function operates like a cmdlet. Therefore, like cmdlets, you can define parameters for your function. So, when a user runs the function, the user can use the parameters to control how the function works.

As a matter of fact, a Function is the best way to build custom scripts. I say this because if you do it right, you avoid hard-coding and use parameters instead.

Using parameters make your function more versatile.

Syntaxes of a PowerShell Function

The syntax of a function is…

Function [<scope:>]<name>
{
  param(
[Parameter(<parameterattributes>) ]
[type]$parameter1],
[Parameter(<parameterattributes>) ]
[type]$parameter2]
)
  dynamicparam {<statement list>}
  BEGIN {<statement list>}
  PROCESS {<statement list>}
  END {<statement list>}
}

A Function may also have this syntax…

function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]
{
  begin {<statement list>}
  process {<statement list>}
  end {<statement list>}
}

Wondering the difference between the first and the second syntax? In the first syntax, you define the parameters within the {} brackets.

On the contrary, in the second syntax, you define the parameters before the {} brackets.

I normally use the second syntax. So, for the purposes of this guide, I will use the first syntax.

Add Parameters to a PowerShell Function:

This section gives you the real deal. In this section, I will be explaining the different elements that make up the parameters of a Function.

I will not only explain though, I will be creating the parameters of a real function.

To help me explain the parameters of a function, here are its main elements:

  • Has the “Function” keyword (required)
  • Defines the scope (optional)
  • Includes the name of the function that you select (required)
  • Any number of named parameters (optional)
  • Includes one or more PowerShell commands that you enclose in braces {}
Apart from the standard defined parameters, a function may also have dynamic parameters. I’ll not be discussing dynamic parameters in this article. To learn about dynamic parameters, visit about_Functions_Advanced_Parameters (link opens in a new browser tab).

In the sub-sections below, I have explained the different elements of a function. Not only that, but I’ll also show you how to create and add those elements to a function.

In this guide, I’ll create a Function called Get-ItemBetweenDates. This function will return files and/or folders based on the modified dates you specify.

Step 1: Add the “Function” Keyword to a Function

When you create a PowerShell Function, you must begin with the word, “Function”. So, let’s start building our Get-ItemsBetweenDates function.

The first word you enter is the word “Function”. This tells PowerShell that it is a function.

Function

Step 2: Define the Scope of the Function

After the word, “Function”, you may optionally define the scope of the function. In PowerShell, you can define the scope for a variable, alias, or function name.

Specifically, you can define multiple types of scope. Since defining the scope of a Function is optional and rarely needed, I’ll not be discussing it in detail in this guide.

To read more about scopes, visit about_Scopes.

Step 3: Add the Name of the Function

After you enter the word “Function” and define the scope of the function, you must then define the name of the function.

Generally, you should name your function following the PowerShell cmdlet’s naming convention. In PowerShell, cmdlets are named in Verb-Noun format.

So, you should name your functions in Verb-Noun format. This brings us to a very important point about cmdlet verbs.

To standardize cmdlet verbs, Microsoft defined a set of approved verbs for PowerShell commands. The good news is that you do not even have to go to the above link to get the approved verbs.

To see a list of approved verbs to use in your PowerShell Function, open PowerShell and run the command below.

Get-Verb

The command returns a list of all the approved verbs in PowerShell.

Parameters Of PowerShell Function

If you run the above command, you’ll see that Microsoft categorized the verbs into 7 groups – Common, Data, Lifecycle, Diagnostic, Communications, Security, and Other.

This brings us to the function we’re creating in this guide, Get-ItemsBetweenDates. “Get” is the verb and it belongs to the Common approved group.

I chose it because the function will “get” files and folders. Then, I chose the noun, “ItemsBetweenDates” because the function will consider modified dates to determine items (files and folders) to “get”.

Now that we have explained how you can select the name of your function, and how I decided on the name of this sample function, let’s add it to the function.

Function Get-ItemsBetweenDates 

Before I proceed to parameters and how to add them, I need to add the {} brackets. When I add the {} brackets, the function will look like this…

Function Get-ItemsBetweenDates  {



}

Step 4: Determine the Parameters and ParameterSetNames Needed

Earlier in this article, I hinted that parameters make your PowerShell Function more versatile. Here is the basic syntax of a parameter param block.

[CmdletBinding(DefaultParameterSetName="ParameterSetName1")]
param(
[Parameter(<parameterattributes>) ]
[type]$parameter1],
[Parameter(<parameterattributes>) ]
[type]$parameter2]
)
If you don’t know about parameters, read my article –
PowerShell Param: Syntax, Types, Attributes, Arguments, And Examples

When you’re creating a Function, you need to think about the parameters you need. In addition to that, you need to determine the type of parameter.

There are a number of parameters you can define but the most common ones are String, int, DateTime, and Switch Parameters. To learn more about these parameters, read Types Of PowerShell Parameters.

So, back to the function, we’re creating in this guide, Get-ItemBetweenDates. If you recollect, I said earlier that this function will return files or folders based on the modified dates you specify.

So, based on the description, we will need to define the following parameters:

  1. Path. This will be a String parameter. It will allow you to define the path to the folder you want the function to get files or folders from.
  2. NumOfDaysFrom. This will be the earliest number of days from today that you want to return files with modified dates.
  3. NumOfDaysTo. This will be the latest number of days from today that you want to return files with modified dates.
Note that NumOfDaysTo should be smaller than NumOfDaysFrom. In essence, the Get-ItemBetweenDates will return all files or folders with a modified date less than or equal to NumOfDaysTo but greater than or equal to NumOfDaysFrom. NumOfDaysFrom and NumOfDaysTo are int parameters. This means that they can only accept integers (numbers)
  1. File. This is a Switch parameter type. By default, Get-ItemBetweenDates returns both files and folders. However, if a user wants this function to return only files, the user will include the File parameter
  2. Directory. Like the File parameter, this is also a Switch parameter type. If a user wants this function to return only folders, the user will include Directory.

I hope I haven’t lost you yet! I really hope so because creating a PowerShell Function is logical thinking business.

With the knowledge of how you want your function to work, you need to plan all parameters in advance. Not only that, but you also need to think through how the parameters will work with one another.

Talking about how the parameters will work with one another, it is time to determine how many ParameterSetNames we need to define in our PowerShell Function.

If you’re wondering, ParameterSetNames sort of “groups” parameters that you can run together in a function. To read more about ParameterSetNames, visit this link – PowerShell Param ParameterSetName Argument.

Now, let’s think about all the parameters I described earlier and how they may work with one another. Based on my descriptions of the parameters, Get-ItemBetweenDates will have 3 ParameterSetNames.

It may help you to better understand the concept of ParameterSetNames if I mention that ParameterSetNames determines the number of syntaxes a PowerShell function will have. For example, if a function has 2 ParameterSetNames, it will have 2 syntaxes. This means that you will have 2 combinations of its different parameters that can run in one command.

Talking about 2 ParameterSetNames for our new function, here is how I arrived at this number:

  1. The first ParameterSetName will include Path, NumOfDaysFrom, and NumOfDaysTo parameters. When you run the Get-ItemBetweenDates command with these parameters, it will return all files and folders that meet with a modified date between NumOfDaysFrom and NumOfDaysTo.

    I will call the theParameterSetName for this “group” Path.
  2. The next theParameterSetName will include Path, NumOfDaysFrom, NumOfDaysTo, and File. If you specify the File parameter with these other 3 parameters, the Get-ItemBetweenDates PowerShell Function will return only files.

    I will call the theParameterSetName for this “group” File.
  3. Finally, is the theParameterSetName I will call Directory. This theParameterSetName will include the Path, NumOfDaysFrom, NumOfDaysTo, and Directory.

Step 5: Add Parameters and ParameterSetNames

Based on the parameters we determined that we needed from the last sub-section, I have created the table below with a summary of the ParameterSetNames and their parameters.

ParameterSetNamesParameters
PathPath, NumOfDaysFrom, and NumOfDaysTo
FilePath, NumOfDaysFrom, NumOfDaysTo, and File
DirectoryPath, NumOfDaysFrom, NumOfDaysTo, and Directory

Since the Path parameter is common to all the ParameterSetNames, I’ll define the 3 ParameterSetNames. Then, beneath them, I will define the Path parameter.

Our updated function will now look like this…

Function Get-ItemsBetweenDates  {
  [CmdletBinding(DefaultParameterSetName="Path")]
  param( 
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=0)]
    [string[]]$Path
)
}
I introduced some parameter attributes that I need to highlight – “Mandatory=$true” and “Position=0”. To learn about these visit PowerShell Param Parameter Attribute

Before I add other parameters and ParameterSetNames, it is a good idea to test the function and ensure it is working as expected. Before we test the function, we have to save it first.

Follow the steps below to save the function:

  1. Create a new folder called Get-ItemsBetweenDates (the same name as the name of the PowerShell Function).
  2. Then, open PowerShell ISE and create a new ISE document.
  3. Next, copy the codes for the function and paste them into the new ISE document
  4. Then, save the function as Get-ItemsBetweenDates.psm1 in the Get-ItemsBetweenDates folder.
How To Add Parameters And ParameterSetNames To A PowerShell Function
  1. Now select all the text in the code (Ctrl + A) then, press F8 to run the code.
  2. Finally, to see the number of syntaxes for the function, enter the command below in the ISE command console and press enter.
Get-Help Get-ItemsBetweenDates

The result of the command shows that the Get-ItemsBetweenDates PowerShell Function has three syntaxes. This was expected because we defined three DefaultParameterSetNames in the function.

Now, it is time to add the NumOfDaysFrom and NumOfDaysTo switch parameters. Here is the ParameterSetNames-Parameters table.

ParameterSetNamesParameters
PathPath, NumOfDaysFrom, and NumOfDaysTo
FilePath, NumOfDaysFrom, NumOfDaysTo, and File
DirectoryPath, NumOfDaysFrom, NumOfDaysTo, and Directory

From the table, we can see that similar to the Path parameter, the NumOfDaysFrom, and NumOfDaysTo parameters are also members of all the ParameterSetNames.

So, we can just add these two parameters beneath the Path parameter. Here is what the updated script looks like…

Function Get-ItemsBetweenDates  {
  [CmdletBinding(DefaultParameterSetName="Path")]
  param( 
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=0)]
    [string[]]$Path,
    [int]$NumOfDaysFrom,
    [int]$NumOfDaysTo
)
}
It is important to point out that parameters defined in the param block are separated by commas. You do not need to add a comma at the last parameter. Also, you can only define a parameter once in a param block. This is why we use ParameterSetNames to define the same parameter in different command options (syntaxes).

Finally, it is time to add the File and Directory parameters. According to our table, the File parameters belong to the File ParameterSetName.

Similarly, the Directory parameter belongs to the Directory ParameterSetName. In the updated version of our PowerShell Function, I have added two parameters.

Function Get-ItemsBetweenDates  {
  [CmdletBinding(DefaultParameterSetName="Path")]
  param( 
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=0)]
    [string[]]$Path,
    [int]$NumOfDaysFrom,
    [int]$NumOfDaysTo,
    [Parameter(ParameterSetName='File', Mandatory=$false)]
    [switch]$File,
    [Parameter(ParameterSetName='Directory', Mandatory=$false)]
    [switch]$Directory

)
}
I just checked the parameter attributes for NumOfDaysFrom and NumOfDaysTo and I released that due to the way I defined the parameters (adding them without explicitly defining attributes), they are not marked as required. To make them required parameters, I will have to explicitly define their parameter attributes. I have updated the script as shown below.

Apart from defining the parameter attributes for NumOfDaysFrom and NumOfDaysTo, I also included the Position attribute to the File and Directory parameters.

Function Get-ItemsBetweenDates  {
  [CmdletBinding(DefaultParameterSetName="Path")]
  param( 
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=0)]
    [string[]]$Path,
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=1)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=1)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=1)]
    [int]$NumOfDaysFrom,
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=2)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=2)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=2)]
    [int]$NumOfDaysTo,
    [Parameter(ParameterSetName='File', Mandatory=$false, Position=3)]
    [switch]$File,
    [Parameter(ParameterSetName='Directory', Mandatory=$false, Position=3)]
    [switch]$Directory
)
}
Here is a summary of the parameter positions: Path is in position 0, NumOfDaysFrom in 1, and NumOfDaysFrom in 2. Similarly, File and Directory are in position 3.

To see the attributes of a parameter, copy the updated script to PowerShell ISE. Then, select all the texts in the code and press F8 to run it.

Finally, run the commands below to see the parameter attributes for the parameters.

Get-Help Get-ItemsBetweenDates -Parameter Path
Get-Help Get-ItemsBetweenDates -Parameter NumOfDaysFrom
Get-Help Get-ItemsBetweenDates -Parameter NumOfDaysTo
Get-Help Get-ItemsBetweenDates -Parameter File
Get-Help Get-ItemsBetweenDates -Parameter Directory

Here is the result of some of the above commands in PowerShell ISE (I removed the script pane to show the command pane in full).

How To Add Parameters And ParameterSetNames To A PowerShell Function

Step 6: Add PowerShell Commands and Statements

Once you have defined your parameters in a PowerShell Function, the next task is to add the actual commands that you want the function to execute.

Before I proceed with this part of the article, it is important to revisit what the Get-ItemsBetweenDates function is designed to accomplish. When you run the function, it returns the files and/or folders in a specified path.

Before I bring in the full function we have built so far, let me first show you the full syntax of the command block of a function.

Function Get-ItemsBetweenDates  {
BEGIN {}
PROCESS {}
END {}
}

You do not have to define the “BEGIN {}”, “PROCESS {}”, and “END {}” blocks but it is a good idea as it helps organize your function.

The first step is to start defining my variables. I will define my variables within the “BEGIN {}” block.

Let’s start by converting the NumOfDaysFrom and NumOfDaysTo parameters from days to dates. Remember that when you run the Get-ItemsBetweenDates command, you specify these two parameters in numbers.

Most importantly, the NumOfDaysFrom parameter is a number further down from the day you ran the command. In essence, I want the function to return the files or folders with the last modified date greater than or equal to NumOfDaysFrom.

To convert the NumOfDaysFrom from the number of days to an actual date, I will use the Get-Date command with the AddDays Method to calculate those dates.

I will save the Get-Date command in a variable called $DateFrom.

$DateFrom = (Get-Date).AddDays(-$NumOfDaysFrom)

Here is the updated function

Function Get-ItemsBetweenDates  {
BEGIN {
$DateFrom = (Get-Date).AddDays(-$NumOfDaysFrom)

}
PROCESS {}
END {}
}

To test this command, I’ll assign a number to the $NumOfDaysFrom parameter manually. Then, run the above command.

$NumOfDaysFrom = 30
$DateFrom = (Get-Date).AddDays(-$NumOfDaysFrom)

I am writing this guide 18th June 2022. Here is the result of the last command.

In the context of our function, if I was to specify the NumOfDaysFrom parameter as 30 (like I did in this example), the function will return all files or folders Greate than or Equal to “19 May 2022 13:51:15”.

How To Add PowerShell Commands And Statements To A PowerShell Function
If you’re wondering why I left out the parameters from the function, to make the function we are building look less complicated. I’ll bring the parameters later.

So, I have defined a variable that converts NumOfDaysFrom from days to date.

$DateFrom = (Get-Date).AddDays(-$NumOfDaysFrom)

Now, I will convert the NumOfDaysTo parameter to date and save the information in the $DateTo variable.

$DateTo = (Get-Date).AddDays(-$NumOfDaysTo)

Here is the updated function.

Function Get-ItemsBetweenDates  {
BEGIN {
$DateFrom = (Get-Date).AddDays(-$NumOfDaysFrom)
$DateTo = (Get-Date).AddDays(-$NumOfDaysTo)
}
PROCESS {}
END {}
}

Now that I have defined the variables I require, it’s time to create the first command. I will now add the

Here is the command that runs when the user does not specify the File or Directory parameter.

Get-ChildItem $Path | Where-Object {($_.LastWriteTime -LE $DateTo) -AND ($_.LastWriteTime -GE $DateFrom)}

I will now update the PowerShell Function by adding the above command in the “PROCESS {}” block.

Function Get-ItemsBetweenDates  {
BEGIN {
$DateFrom = (Get-Date).AddDays(-$NumOfDaysFrom)
$DateTo = (Get-Date).AddDays(-$NumOfDaysTo)
}
PROCESS {
Get-ChildItem $Path | Where-Object {($_.LastWriteTime -LE $DateTo) -AND ($_.LastWriteTime -GE $DateFrom)}
}
END {}
}

At this stage, I will re-introduce the parameters. Once we have the parameters in the function, we can run our first live test!

Function Get-ItemsBetweenDates  {
  [CmdletBinding(DefaultParameterSetName="Path")]
  param( 
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=0)]
    [string[]]$Path,
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=1)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=1)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=1)]
    [int]$NumOfDaysFrom,
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=2)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=2)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=2)]
    [int]$NumOfDaysTo,
    [Parameter(ParameterSetName='File', Mandatory=$false, Position=3)]
    [switch]$File,
    [Parameter(ParameterSetName='Directory', Mandatory=$false, Position=3)]
    [switch]$Directory
)
BEGIN {
$DateFrom = (Get-Date).AddDays(-$NumOfDaysFrom)
$DateTo = (Get-Date).AddDays(-$NumOfDaysTo)
}
PROCESS {
Get-ChildItem $Path | Where-Object {($_.LastWriteTime -LE $DateTo) -AND ($_.LastWriteTime -GE $DateFrom)}
}
END {}
}

To test the function, copy the above code into the file in ISE. To show that the default command works, I have run the command below…

Get-ItemsBetweenDates -Path D:\report -NumOfDaysFrom 18 -NumOfDaysTo 13

The above command should return all files and folders in the path D:\report that were last modified between 18 days ago and 13 days ago.

Here is the result…

So, did the function work? Let’s find out.

My current date and time are (I got this by running Get-Date in PowerShell)…

18 June 2022 14:13:07 

I8 days ago, the date and time were…

(Get-Date).AddDays(-18)
31 May 2022 14:15:49

Also, I3 days ago, the date and time were…

(Get-Date).AddDays(-13)
05 June 2022 14:17:17

If the Get-ItemsBetweenDates works as designed, the files and folders returned will have a LastWriteTime between “31 May 2022 14:15:49” and “05 June 2022 14:17:17” (inclusive).

According to the result of the command of the Get-ItemsBetweenDates, the files returned have the following LastWriteTime:

31/05/2022     21:05
31/05/2022     21:03
04/06/2022     16:32
03/06/2022     00:54
31/05/2022     15:20

To make the co parison easier, I will now add the comparison dates beneath the above dates:

31/05/2022     21:05
31/05/2022     21:03
04/06/2022     16:32
03/06/2022     00:54
31/05/2022     15:20
/////////////////////////
31 May 2022 14:15:49
05 June 2022 14:17:17
I apologize to my American readers. The LastWriteTime dates for my files are in the British format. Here are the American formats:

05/31/2022 21:05
05/31/2022 21:03
06/04/2022 16:32
06/04/2022 00:54
31/05/2022 15:20
//////////////////////////////
May 31 2022 14:15:49
June 05 2022 14:17:17

Now, back to our test results, it is obvious that our function is working as expected. The LastWriteTime dates for all the files returned fall between May 31 2022 and June 05 2022.

As much as I like to celebrate at this stage, I cannot because the PowerShell Function is not yet ready.

The next task is to introduce the File and Directory parameters. To do this, I will use the PowerShell IF-ELSEIF statement.

Here is the updated code…

Function Get-ItemsBetweenDates  {
  [CmdletBinding(DefaultParameterSetName="Path")]
  param( 
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=0)]
    [string[]]$Path,
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=1)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=1)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=1)]
    [int]$NumOfDaysFrom,
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=2)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=2)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=2)]
    [int]$NumOfDaysTo,
    [Parameter(ParameterSetName='File', Mandatory=$false, Position=3)]
    [switch]$File,
    [Parameter(ParameterSetName='Directory', Mandatory=$false, Position=3)]
    [switch]$Directory
)
BEGIN {
$DateFrom = (Get-Date).AddDays(-$NumOfDaysFrom)
$DateTo = (Get-Date).AddDays(-$NumOfDaysTo)
}
PROCESS {
   IF ($File) {
        Get-ChildItem $Path -File | Where-Object {($_.LastWriteTime -LE $DateTo) -AND ($_.LastWriteTime -GE $DateFrom)} 
    } ELSEIF ($Directory) {
        Get-ChildItem $Path -Directory | Where-Object {($_.LastWriteTime -LE $DateTo) -AND ($_.LastWriteTime -GE $DateFrom) }
} ELSE{
    Get-ChildItem $Path | Where-Object {($_.LastWriteTime -LE $DateTo) -AND ($_.LastWriteTime -GE $DateFrom)}
}
}
END {}
}

The only change I made was to introduce IF-ELSEIF-ELSE statement in the function’s “PROCESS {}” block. Essentially, my code says:

“IF a user specifies the $File parameter, run the Get-ChildItem command with its File parameter”

“ELSEIF a user specifies the $Directory parameter instead, run the Get-ChildItem command with its Directory parameter”.

“ELSE if nether the $File nor $Directory parameter is specified, run the Get-ChildItem command without its Directory or File parameters”.

It is time to perform another test. If you have been performing the hands-on tasks in this article, copy the last updated code and replace the one in PowerShell ISE. Run the code and finally, test it.

I will test mine with the command below:

Get-ItemsBetweenDates -Path D:\PS-Tutorial -NumOfDaysFrom 1 -NumOfDaysTo 0 -File
Get-ItemsBetweenDates -Path D:\PS-Tutorial -NumOfDaysFrom 1 -NumOfDaysTo 0 -Directory

Both commands are supposed to return the files (first command) and folders (second command) that were modified today.

Here are the results – the first command returned a file while the second command returned a folder.

How To Add PowerShell Commands And Statements To A PowerShell Function

If I run the command without specifying the File or the Directory parameters, it returns the file and folder modified today.

Get-ItemsBetweenDates -Path D:\PS-Tutorial -NumOfDaysFrom 1 -NumOfDaysTo 0

The PowerShell Function is working as expected. However, I want to modify the output.

Specifically, I want to display the “Name” and the “Modified Date”.

To do this, I’ll save the result of the Get-ChildItem commands to a variable. Then, at the “END {}” block of the function, I’ll create a final report using the Select-Object command.

Here is the final Get-ItemsBetweenDates PowerShell Function.

Function Get-ItemsBetweenDates  {
  [CmdletBinding(DefaultParameterSetName="Path")]
  param( 
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=0)]
    [string[]]$Path,
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=1)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=1)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=1)]
    [int]$NumOfDaysFrom,
    [Parameter(ParameterSetName='Path', Mandatory=$true, Position=2)]
    [Parameter(ParameterSetName='File', Mandatory=$true, Position=2)]
    [Parameter(ParameterSetName='Directory', Mandatory=$true, Position=2)]
    [int]$NumOfDaysTo,
    [Parameter(ParameterSetName='File', Mandatory=$false, Position=3)]
    [switch]$File,
    [Parameter(ParameterSetName='Directory', Mandatory=$false, Position=3)]
    [switch]$Directory
)
BEGIN {
$DateFrom = (Get-Date).AddDays(-$NumOfDaysFrom)
$DateTo = (Get-Date).AddDays(-$NumOfDaysTo)
}
PROCESS {
   IF ($File) {
        $report = Get-ChildItem $Path -File | Where-Object {($_.LastWriteTime -LE $DateTo) -AND ($_.LastWriteTime -GE $DateFrom)} 
    } ELSEIF ($Directory) {
        $report = Get-ChildItem $Path -Directory | Where-Object {($_.LastWriteTime -LE $DateTo) -AND ($_.LastWriteTime -GE $DateFrom) }
} ELSE{
        $report = Get-ChildItem $Path | Where-Object {($_.LastWriteTime -LE $DateTo) -AND ($_.LastWriteTime -GE $DateFrom)}
}
}
END {   
    $report | Select-Object -property `
   @{Label=”File/Folder Name”;Expression={$_.Name}}, 
   @{Label=”Modified Date”;Expression={$_.LastWriteTime}}
}
}

If you followed this guide from the beginning, you have just created your first function!

Frequently Asked Questions

1. What is a PowerShell Function?

A PowerShell Function is a list of named PowerShell commands (statements) that you can call. In essence, a Function is like a script.

The only difference is that you do not name a script but you can name a function. Then, you can call the name of the function like a PowerShell cmdlet.

2. How do you write a Function in PowerShell?

To write a function in PowerShell, start with the word “Function” followed by the name of the function. For example: Function Get-ItemsBetweenDates.

Then, enter the braces {}. Finally, within the braces {}, enter your PowerShell commands or statements.

Here is the full sample function:

Function Get-ItemsBetweenDates {
enter statements or command here
}

3. What is CmdletBinding()?

CmdletBinding is an attribute of the PowerShell param block. The param block is used to define parameters in a PowerShell function.

4. What is ParameterSetName in PowerShell?

ParameterSetName is a parameter param argument. It “groups” all parameters that can be used in the same command syntax.

5. What is ValueFromPipeline in PowerShell?

ValueFromPipeline is a parameter augment that defines if a parameter can accept values from a PowerShell pipeline.

If you ValueFromPipeline=$true, it means that that parameter can accept input from pipelines. However, if you define ValueFromPipeline=$false, then, the parameter cannot accept input from the pipeline.

Conclusion

If you want to take your PowerShell scripting to the next level, you must learn how to create functions. When you progress from writing scripts to writing functions, you can build functions that you can use with parameters.

Using parameters means you avoid hard coding and can make your functions work in different scenarios. Consider the function I built while writing this article, if it was a script, I would have hard-coded all that parameters into the script.

If they were hard-coded, anytime I needed to change the path of the folder, for example, I would have had to edit the script. However, with the function I created, I can just provide the Path parameter!

I admit that learning about functions is a fairly advanced topic. But I hope I was able to make it easier for you to learn.

Let me know what you think about this article by clicking an option in the “Was this page helpful?” question below.

Finally, if you’re serious about learning PowerShell you should read more PowerShell guides on our Windows PowerShell Explained page.

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

We're committed to writing accurate content that informs and educates. To learn more, read our Content Writing Policy, Content Review Policy, Anti-plagiarism Policy, and About Us.

However, if this content does not meet your expectations, kindly reach out to us through one of the following means:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

2 thoughts on “Advanced PowerShell Function Explained with Examples”

Leave a comment