Create PowerShell Functions

When we have a block of code that will be used over and over again, we should consider putting it into a function. That way, the code block can be reused and managed much more easily than writing the same piece of code multiple times in the script.

Using functions also helps improve code readability and maintainability. With a meaningful function name, we can quickly identify the code and understand what it is supposed to do. If there is a problem in the code, we only have to fix it in one place.

So let’s take a look at some examples of PS Function.
## Example 1
function ShowMyProcess
{
Get-Process
}
ShowMyProcess

Above is a very basic function that shows information about the processes running on my computer. It doesn’t require any parameters.
## Examples 2
function ShowMyFileList ($filepath, [bool]$isRecur)
{
if($isRecur)
{
Get-ChildItem -Path $filepath -Recurse
}
else
{
Get-ChildItem -Path $filepath
}
}
ShowMyFileList "C:\" $true

The second example is a little bit more complex than the first one. The function requires a couple of parameters and it returns results based on the input values. So in the above case, we are expecting the function to list all the files under C drive, in a recursive manner.

Extract txt files from a zip archive using PowerShell

Scenario:

You’d like to extract all txt files from a zip archive, and then remove the archive file if successful,

PS Script:

& "C:/Program Files/WinRAR/WinRar.exe" x -r ".zip" ".txt" | Write-Output
if($?)
{
Remove-Item "*.zip"
}

Explanations:

& is the call operator, also known as invocation operator, which runs an external executable. In above example, it runs an WinRaR command line, which is installed under “C:\Program Files\” directory.

The following X -r are the command arguments for WinRaR command line. X means it’s an extraction operation, and -r is a switch that indicates recursion. Please refer to this online manual for more WinRaR commands and switches.

$? is a special token that returns boolean (True or False) value, indicating whether or not previous command ended with an error. So in our case, it tells the if conditional statement whether calling Remove-Item cmdlet is needed or not.

Recommended Resource

PowerShell: Running Executables

PowerShell Special Characters And Tokens

PowerShell and external commands done right

Bulk delete specific files using PowerShell

Scenario:

You’d like to remove a bunch of specific files that contain prefix of _del from a given directory “C:\OldFiles“.

PS Script:

Get-ChildItem -Path "C:\OldFiles" | Where-Object {$_.Name -like "*_del.*"} | Remove-Item -Verbose

Explanations:

Above script can be divided into 4 parts,

  1. Get-ChildItem -Path “C:\OldFiles”
  2. Vertical Bar (|) or also known as, Pipeline
  3. Where-Object {$_.Name -like “*_del.*”}
  4. Remove-Item -Verbose

Get-ChildItem is one of the very basic PS cmdlets that gets the items and child items in one or more specified locations. In above scenario, we have specified the location to be C:\OldFiles using -Path parameter.

Pipeline (|) is used between commands to create the pipeline. We work from left to right down the pipeline. The output of one command effectively becomes the input of the next command.

Where-Object is another PS cmdlet that is being used very often. It provides a way to filter data returned by other cmdlets.

Things here to be aware of:

The where clause is enclosed within curly braces; in addition, the $_ notation is used to represent the default object (that is, the object being transferred across the pipeline). Last, but surely not least, notice the comparison operator being used to indicate greater than: it’s -gt as opposed to >. Windows PowerShell does not use the standard arithmetic comparison operators; instead, it uses operators such as these:

  • -lt — Less than
  • -le — Less than or equal to
  • -gt — Greater than
  • -ge — Greater than or equal to
  • -eq — Equal to
  • -ne — Not equal to
  • -like – Like; uses wildcards for pattern matching

Remove-Item is a cmdlet that deletes the specified items. In normal case, -Path parameter should be expected. However, in the example above, the files that will be removed are sent down through the pipeline from Get-ChildItem and Where-Object cmdlets. In other words, only those specific files will be removed by Remove-Item cmdlet.

-Verbose is a parameter that allows to output some extra info about the cmdlet operation. For example, the message “VERBOSE: Performing the operation “Remove File” on target “C:\OldFiles\1_del.txt”.” will be displayed in the console window.

 

Recommended resources:

Windows PowerShell – Conditional Operators

Windows PowerShell – Pipeline Symbol (|) or (¦)