Regular Expressions is often referred to as wizardry or magic and for that reason I stayed away from it for most of my career. I used it only when I had to and most of the time just reused examples that I found online. There’s nothing wrong with that of course, but I never took the time to learn it. I thought it was reserved for the elite. Turns out that it’s not that complicated and that I had been using it for years without knowing it. In an effort to shorten the learning curve for others and to show you the value of learning regular expression I’ve written a blog post titled A Practical Guide for Using Regex in PowerShell. It will walk you through how to use regular expression in PowerShell and gives you a glimpse into how powerful regular expression is. Below is an example of how to use regular expression to extract a user’s name from their distinguished name in Active Directory. To learn more check out this blog post. Topics Covered
Do you spend hours a day in PowerShell? Switching back and forth between PowerShell windows getting you down? Have you ever wanted “Quake” mode for your terminal? If we are going to spend so much time in PowerShell, we may as well make it pretty. Check out the Ultimate PowerShell Prompt Customization and Git Setup Guide for how to:
At the beginning of July, we welcomed our 3rd son into the world. As days past my wife and I would say, “wow, he’s 11 days old. Can you believe it?!”. I’m sure parents out there are relating to this! This gave me an idea for a fun script that would get your age in years, months and days, tell you how many days until your birthday and your star sign. I wanted date of birth passed to the function as ‘dd/MM/yy’. To keep to this format, I’m using the ‘ValidatePattern’ Advanced Parameter with a Regular Expression (Regex). The regular expression, “^(0[1-9]|[12]\d|3[01])/(0[1-9]|1[0-2])/(\d{2})$”, will only allow a date in the format of 01/01/16, for example. Briefly, here is regex syntax I used in some of the expression: ^ Start of string ( .. ) Capturing group (0[1-9] Match two digits that make up the day. This accepts numbers from 01 to 09 | Acts like a Boolean OR. /d match any digital character [12] match any character in the set / used to divide the date numbers {2} Exactly two times $ End of string Now that my function parameter variable $Bday has a date, its passed to get-date to be converted from a string to a date. The date in variable $cDate will look like this, ‘01 January 2016 00:00:00’. The next line in the code will use todays date and subtract the date passed in $cDate variable. The $diff variable will contain the following data which we will use to get our age in years, months and days: Days : 212 Hours : 12 Minutes : 40 Seconds : 20 Milliseconds : 533 Ticks : 183624205335135 TotalDays : 212.528015434184 TotalHours : 5100.67237042042 TotalMinutes : 306040.342225225 TotalSeconds : 18362420.5335135 TotalMilliseconds : 18362420533.5135 I’ve contained this first part in our Begin block. The Process block does the main code. Now I need to get my age in Years, Months and Days. This is where the [math] data type is used. I’m using the ‘Truncate’ property as I don’t want to do anything fancy like round up my numbers. Adding the .typename of Days to my $diff variable and dividing by $daysInYear variable I can get my age in years. The next two, months and days required a tweak to the algorithm. I ended up using a maths term called a ‘Mod’. Now I’m not talking about youth culture and style in the sixties (Mods and rockers anyone ??), but the Modulus Math Operator. Basically the Modulus Operator returns the remainder when the first number is divided by the second. So for example: 1 mod 3 = 1 (or 1 % 3 = 1) 2 mod 3 = 2 3 mod 3 = 0 4 mod 3 = 1 The operator sign used is % for Modulus. Not to be confused for the alias of foreach in PowerShell. For days in a month, I used the average of 30. I thought it would be fun to add the star sign as well. I was after something that could tell me, “is this date in this date range?”. One of the properties of ‘get-date’ is DayOfYear. Finding if a number is in a range is pretty straight forward, For example:
“To be or not to be”. Without getting into a debate over whether Shakespeare was musing about being a logician, suffice to say that in writing prose, the rules of when and how to use quotation marks are relatively clear. In PowerShell, not so much. Sure, there is an about_Quoting_Rules documentation page, and that is a good place to start, but that barely covers half the topic. It assumes you need quotes and then helps you appreciate some of the factors to consider when choosing single quotes or double quotes. But do you need quotes? Remember PowerShell is a shell/command language so “obviously” you can do things like this:
By the time you are using PowerShell to automate an increasing amount of your system administration, database maintenance, or application-lifecycle work, you will likely come to the realization that PowerShell is indeed a first-class programming language and, as such, you need to treat it as such. That is, you need to do development in PowerShell just as you would with other languages, and in particular to increase robustness and decrease maintenance cost with unit tests and–dare I say–test-driven development (TDD). I put together several articles on getting started with unit tests and TDD in PowerShell using Pester, the leading test framework for PowerShell. This series introduces you to Pester and provides what I like to call “tips from the trenches” on using it most effectively, along with a gentle prodding towards a TDD style. Part 1: Getting Started with the Pester Framework Starting with the ubiquitous “Hello, World”, this introduces Pester, showing how to execute tests, how to start writing tests, and the anatomy of a test. Part 2: Mock Objects and Parameterized Test Cases To be able to create true unit tests, you need to be able to isolate your functions and modules to be able to focus on the component under test; mocks provide great support for doing that. Another topic of “power” unit tests is making them parameterizable, i.e. being able to run several scenarios through a single test simply by providing different inputs. Part 3: Validating Data and Call History The final part of this series provides a “how-to” for several other key parts of Pester: how to validate data, how to determine if something was called appropriately, and how to address a particular challenge with Pester, validating arrays. I’ve included a library for array validation to supplement Pester. For a more general treatment of unit tests, I refer you to Roy Osherove’s canonical text on the subject, The Art of Unit Testing.
Having an understanding of your systems performance is a crucial part of running IT infrastructure. If a user comes to us and says “why is my application running slowly?”, where do we start? Is it their machine? Is it the database server? Is it the file server? The first thing we usually do is open up perfmon.exe and take a look at some performance counters. You then see the CPU on the database server is 100% and think _ “was the CPU always at 100% or did this issue just start today? Was it something I changed? If only I could see what was happening at this time yesterday when the application was running fine!". _It might take you a few hours to find the performance issue on your infrastructure, and you are probably going to need to open up perfmon.exe on a couple of other systems. There is a better way! What if you could turn your Windows performance counters into dashboards that look like this? How much time would you save? Using a combination of the open source tools InfluxDB to store the performance counter data, **Grafana **to graph the data and the Telegraf agent to collect Windows performance counters, you will be a master of your metrics in no time! Read the detailed walk through over at hodgkins.io
Long has it been known how to easily document your PowerShell source code simply by embedding properly formatted documentation comments right along side your code, making maintenance relatively painless…
But if you advanced to writing your PowerShell cmdlets in C#, you have largely been on your own, either hand-crafting MAML files or using targeted MAML editors far removed from your source code. But not anymore. With the advent of Chris Lambrou’s open-source XmlDoc2CmdletDoc, the world has been righted upon its axis once more: it allows instrumenting your C# source with doc-comments just like any other C# source: All of the above provides fuel for Get-Help, i.e. providing help one cmdlet at a time. But we are a civilized people; we also need a web-based version of our full custom PowerShell API. That is, a hierarchical and indexed set of Get-Help pages for all the cmdlets in our module. For this task, my own open-source effort, DocTreeGenerator, nicely fills the gap, requiring very little beyond the doc-comments described above to do the complete job. I have written extensively on using both XmlDoc2CmdletDoc and DocTreeGenerator, and just this week, released a one-page wallchart that shows how all the pieces work together: Here’s the link to get you started on this fun journey: Unified Approach to Generating Documentation for PowerShell Cmdlets
There is a lot of documentation out there for interacting with Microsoft Office including Outlook, Excel, Word, etc with Visual Basic for Applications (VBA). A lot of time you may only be able to find VBA examples. VBA’s require template files to be sent to the desktop and are a real hassle when trying to automate across multiple machines. There are not many A to B examples of translating VBA to PowerShell so I took a problem I had solved in the past and presented the before and after. Hopefully it will provide enough information to allow others to convert VBA code into PowerShell for their scenarios. You can check out the full article on PowerShellBlogger.com.
If you are not on Office 365 or have a tenant set up with Microsoft yet, now is the time to reserve your tenant name! With utilizing Office 365, a lot of administration is only available from a PowerShell session. There is a mix of outdated information on what you actually need to install and execute in order to connect to all of the Office 365 services. As a result, I accumulated and wrote up the current download requirements and commands to connect and administer every Office 365 service from one PowerShell session. I hope this saves everyone a lot of time and effort! Head over to PowerShellBlogger.com to read the full article here.
ChatOps is a term used to describe bringing development or operations work that is already happening in the background into a common chat room. It involves having everyone in the team in a single chat room, then bringing tools into the room so everyone can automate, collaborate and see how automation is used to solve problems. In doing so, you are unifying the communication about what work gets done and have a history of it happening. ChatOps can be supplemented with the use of tools or scripts exposed using a chat bot. Users in the chat room can talk to the bot and have it take actions on their behalf, some examples of this may be: