Powershell: A Scripting Language for .NET Junkies and Administrators

Introduction

Have you ever tried using the wrong tool for the wrong job? Using a butterknife in place of a flat-head screwdriver?  Hitting Caps Lock every time you want to capitalize just one letter? Using VIM to write a program when you could be doing it in Nano…just kidding.  Well, let me tell you of a problem I once had using a great shell but for the wrong OS. As many of you know, I started my development career by learning Python and the Linux CLI in hopes that I could be transferred from Desktop Support to Application Development for a former employer.  I found many of the built in tools in BASH so useful, that I would sometimes go as far as downloading Cygwin so that I could use them in a Windows environment. And that right there was a problem…   I knew Windows had a tool, called Powershell, that was built to serve as a command-line utility and a means to automate daily tasks, but I kept using BASH because it was what I was familiar with.  After having issues getting Cygwin to work properly on my current workstation and learning of a project involving cleanup of a Windows 2016 file-server, I finally broke and started learning it. I knew that I would have no issues figuring out how to use it, but I did not expect that I would love using it more than BASH.   Before I go any further, I want you to know that this post is NOT about claiming Powershell is better than BASH.  BASH was designed and works best for Unix/Unix-like systems, and Powershell was designed and works best for Windows (though you can use it on Linux and Mac thanks to .NET Core).  This post is merely an explanation of Powershell and why I love using it.  

Verb!  That’s What’s Happening!

Most of the commands in shell scripting languages somewhat resemble what the do.  Using BASH as a reference, ls is for list, cp is for copy, mv is for move, ect.  But there are other commands that are not so descriptive with their names.  Can you get “search for string” out of grep?  What about “find text and replace with” from awk?     One of the most notable features of Powershell is that it does away with this guesswork by using a strict Noun-Verb syntax.  Need to search for all occurrences of the word “test” in all text files contained in a specific directory? Simple, type:   Select-string “test” C:\your\path\here\*.txt   What if you want to change directories to C:\Program Files.  Type: Set-Location C:\      The best part of the verb-noun approach is that you do not need to memorize a list of cmdlets (Powershell’s name for commands) to know what they do.  I found that once I used Powershell long enough, I was able to use cmdlets on the fly without needing to look them up, as their names described the action and what would be impacted by it.  

Different Language, Same Framework

.NET developers who need a quick script can take joy in the fact that Powershell is written in their favorite framework!  If you are well-versed in C# or VB.NET, you will have no trouble picking up on Powershell. The same methods you use in your .NET programs will be accessible to you in Powershell.  Additionally, all your favorite .NET DLLs can easily be attached to your script so you can take advantage of your favorite libraries.  

A Scripting Language with Class

Like Python, Powershell has the ability to utilize classes and objects in its scripts.  As we all know, an object is a collection of related attributes and actions. Let’s use a .NET DateTime object as an example.  Below, you can see I am saving the current datetime in a DateTime object called $dt.   Looking at the surface, you may think “big deal, you’re just printing out the current date and time to the console”.  But I promise, it is much more than that. Watch what happens when I type “$dt.” to the console, hit the tab key, then hit Enter.   Okay, so it’s the current date and time again.  But what if I hit the Tab key one more time?   $dt.Day gives us the current day of the month (The 4th day of November at the time of this writing).  So we clearly see that $dt is a DateTime object and we are able to access its attributes. But what about the objects actions?  Let’s type “$dt.” to the console again and hit tab a few times.   The DateTime object gives us access to a method called adddays.  Let’s see what happens if we place 1 as an argument.   A day has been added to our current DateTime.  So $dt is more than use a single value, it is a collection of related attributes and actions pertaining to the current date time.  

Automate Your Workflow

While it can be a powerful tool for developers, Powershell was built primarily for Windows sysadmins to help automate operations, such as setting up new users in Active Directory or creating Sharepoint sites in Office 365.  As stated earlier, I am currently using it to help clear space in one of our file servers. Instead of manually seeking out files older than a certain age, I have a script that will seek them out and email a report to the directory owner with a list of files that are subject to be purged.  Another script related to this project will move old files to an Archive folder, which can later be deleted from our server. These scripts help us save time and decrease the chance of human error being responsible for purging the wrong files.  

Dynamic Scoping

One unusual aspect of Powershell that sets it apart from other languages is its ability to take advantage of dynamic scoping.   This means that any variable you make in a script is accessible anywhere. Take a look at the program below for an example.   Conventional wisdom teaches us that we SHOULD get an error when our program executes line 5, because $val should not exist outside of the if statement.  But when we run the program…   We see that not only are we able to make use of $val, but we can see the string stored inside it.    

Interactive Shell

By now,  you are already aware that you can use Powershell in a console.  Like BASH and Python, this feature allows you to make quick changes that do not need to be scripted, or allows you to test a specific line of code before putting it in your program.  I always keep a Powershell console open at work, and have used it as a replacement to the traditional CMD Prompt. So if you need to ping a server or to build your Angular project, you can trust that the Powershell console will handle your task.  

Where to Learn the Language

As with all .NET languages, the best place to learn is from the creators of it themselves.  Microsoft goes to great lengths to help you learn Powershell because they want as many people as possible to use their product.  My personal suggestion is to watch “Getting Started with Microsoft Powershell 3.0” on the Microsoft Virtual Academy here.  One of the presenters in that video series is the lead architect of Powershell himself, Jeffrey Snover.  You can also view the official documentation here.     Another great resource some of my fellow IT admins have swore by (but I have yet to read) is Don Jones’ “Learn Windows Powershell in a Month of Lunches”.  You can also find plenty of tutorials on Youtube or developer blogs.    

Conclusion

Whether you are a .NET developer that needs a small program or Windows sysadmin that is looking to automate, Powershell is an excellent tool that is designed to help you quickly build scripts in a Windows environment.  Microsoft stack developers will find the language easy to pick up as it is a member of the .NET framework family, and administrators will love the power it gives them to automate their daily operations.   Have any questions, comments, or concerns about this post?  Notice anything that can be added or approved? If so, please let me know in the comments.  I look forward to hearing from you!