Build Your Own PowerShell Cmdlet: Part 5 of 9

Doctor Scripto

Summary: Microsoft Windows PowerShell MVP, Sean Kearney, continues a series of guest blogs detailing building your own cmdlet.

Microsoft Scripting Guy, Ed Wilson, is here. Guest blogger and Windows PowerShell MVP, Sean Kearney, has written a series about building cmdlets. For more about Sean, see his previous guest blog posts.

Note This is Part 5 of a nine-part series about building your own Windows PowerShell cmdlet. Read the entire series as it unfolds.

Here’s Sean…

Yesterday, we introduced some common parameters that are now available to our cmdlet:

  • -Verbose

  • -Debug

  • -WarningAction

  • -WarningVariable

  • -ErrorAction

  • -ErrorVariable

  • -OutVariable

  • -OutBuffer

Now we can modify our existing advanced function to leverage some of these parameters.

We are already using the Write-Error cmdlet. We can also add Write-Debug in various points of the script to show the values of our variables for troubleshooting.

function global:ADD-LOGFILE{














WRITE-DEBUG “`$Folder: $Folder”

WRITE-DEBUG “`$Preface: $Preface”

WRITE-DEBUG “`$Extension: $Extension”


# GET the Current Date for our Logfile



WRITE-DEBUG “`$Today: $Today”

# Extract the Date removing the “/”



WRITE-DEBUG “`$Date: $Date”


# Extract the Time removing the “:”



WRITE-DEBUG “`$Time: $Time”


# Build our Filename



WRITE-DEBUG “`$Logfilename: $Logfilename”


# Test and ensure file does not already exist


IF (TEST-PATH -path $Logfilename)


{ WRITE-ERROR –message “Error: $Logfilename exists.” –category ‘WriteError’


# If file exists, return a status of Boolean $False for Unsuccessful


RETURN $Logfilename,$FALSE }






# Create logfile


NEW-ITEM –Type File -path $Logfilename -Force | OUT-NULL

WRITE-DEBUG “$Logfilename successfully created”


# Return the Full path and filename if successful


RETURN $Logfilename,$TRUE




We’ll save this as a new Windows PowerShell script called addlogcmdlet.ps1 and execute it to create the new cmdlet in memory.

With these new changes to our cmdlet, we can troubleshoot and view the variables within the cmdlet (or whatever output we choose reveal) by adding the Verbose parameter.

Image of command output

We can even have our cmdlet pause and ask us what to do if an error occurs by leveraging the ErrorAction parameter.

Image of command output


Thank you, Sean. The cmdlet is really coming together. Nice additions today. Guest Blogger Week will continue tomorrow when Sean will talk more about building a cmdlet.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy



Discussion is closed.

Feedback usabilla icon