Hey there checkyourlogs.net fans!

In my last post, I described a quick bit of PowerShell code for pinging an IP range. Paste this code into VSCode or the ISE, run, and watch the results. Quick and dirty. Once I had this working, I wanted more. For instance, I want to run the code from a PowerShell command-line, passing parameters to change how it performs. To reach this end, I need to transform the code into a function complete with parameters. Don’t let the word function freak you out. Basic PowerShell functions don’t require 20 years of programming experience to understand or create. You’ll see what I mean in a moment.

First step, wrap our existing code within a function code block. Before the existing code, add a line with the function keyword, a function name, and an opening curly brace. After the code, close the function with a closing curly brace.

function FunctionName {
code to execute

Quick tip: Create function names following PowerShell’s verb-noun format. I like to use PowerShell approved verbs along with a noun describing the function. Finding approved verbs is easy, use the cmdlet <PS> Get-Verb </PS>. This screenshot shows a partial list of approved verbs output by the <PS> Get-Verb </PS> cmdlet.

Adding a function code block, our code becomes a function named Ping-Sweep.

Next order of business turning our control variables into parameters. Basic process, we wrap our variable declarations into a parameter block using the Param keyword along with opening and closing parenthesis. Within the parameter block we define parameters along with their details such as if their mandatory, what type they are, and even if they have default values. Don’t worry if reading this seems a bit confusing, look at the code below.

Param (
# Subnet identifier for ping sweep – NO default
# Host IP to start ping sweep – default to 1
[int]$start = 1,
# Host IP to finish ping sweep – default to 254
[int]$end = 254,
# Number of times to attempt each ping – default to 1
[int]$ping = 1,
# Path and filename for results file - default to C:\Temp\Output.csv
[string]$OutPath ="C:\Temp\Output.csv"

Our function just became a great deal more flexible. Call the function with complete control over which IPs to ping and where to create the output file. Excellent!

Save the new code as a PowerShell script file with a .ps1 extension. Then dot-source this file into a PowerShell session and the function is ready to use. Easiest route to dot-source is change to the script’s directory, type period space period backslash filename i.e. . .\pingsweep_function.ps1. Once dot-sourced run the function. Type the function name along with parameters and watch the magic happen.

This function is off to a great start! My next post focuses on adding functionality for a more robust, easier to use tool. Talk to you then, checkyourlogs.net fans!