Search
Generic filters
Exact matches only
Filter by Custom Post Type

Pester – Parameters and Hashtable Fun!

I have written a short excerpt on how to pass parameters from an object to a Pester test. I have turned this into a function: Invoke-POVTest.

The function is primarily for operational validation tests, where you might have a single operational test but you need to test multiple cases. (Sorry, I am not quite sure if I described it properly).

I'll be interested in any feedback.

 

Link to blog post here.

 

PowerShell Gotchas

You can certainly find a number of articles around that present PowerShell pitfalls that can easily trip you up if you are not careful. I took a different approach in my three-part series, A Plethora of PowerShell Pitfalls.

The first two parts are presented in quiz format, together covering the top 10 "gotchas". They will help you test your awareness to see if you even realized the danger and did not know you've been skirting those traps for awhile. After you've had an opportunity to consider the conundrums presented, I then go into detailed explanations for why they happen and how to fix them.

The third and final part is a compendium of all the common "gotchas" that I put together after reviewing all the other lists out there. The more than 35 entries in the list cover, I believe, a good 98% of the issues you would likely encounter. Yes, there are more esoteric pitfalls as well, but I ran out of web page... 🙂

Part 1: Pesky Parameter Problems

Part 2: A Portion of Potential Puzzles

Part 3: The Compendium

 

Pitfalls of the Pipeline

Pipelining is an important concept in PowerShell. Though the idea did not originate with PowerShell (you can find it used decades earlier in Unix, for example), PowerShell does provide the unique advantage of being able to pipeline not just text, but first-class .NET objects.

Pipelining has several advantages:

  • It helps to conserve memory resources. Say you want to modify text in a huge file. Without a pipeline you might read the huge file into memory, modify the appropriate lines, and write the file back out to disk. If it is large enough you might not even have enough memory to read the whole thing.
  • It can substantially improve actual performance. Commands in a pipeline are run concurrently-even if you have only a single processor, because when one process blocks, for example, while reading a large chunk of your file, then another process in the pipeline can do a unit of work in the meantime.
  • It can have a significant effect on your end-user experience, enhancing the perceived performance dramatically. If your end-user executes a sequence of commands that takes 60 seconds, then until 60 seconds has elapsed he/she would see nothing without pipelining, whereas output could start appearing almost immediately with pipelining.

PowerShell provides a variety of techniques for using pipelining but it is all to easy to do it wrong, so you think you are pipelining but in fact you are not. In my article Ins and Outs of the PowerShell Pipeline, I discuss the most common things that can trip you up with implementing pipelining and how to avoid them.

A Practical Guide for Using Regex in PowerShell

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.

matches

Topics Covered

  • -match operator
  • -match operator with regular expression metacharacters
  • -notmatch with where-object
  • -replace operator
  • -split operator
  • Select-String
  • Switch Statements
  • Regex Object

Ultimate PowerShell Prompt Customization and Git Setup Guide

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:

  • Install and customize ConEmu
  • Enable Quake Mode for your terminal
  • Setup your PowerShell Profile
  • Install and use Posh-Git
  • Generate and use SSH Keys with GitHub
  • Squash Git commits

A date with PowerShell

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:

 5 -in 1..10 

Which gives a Boolean result.

Now if I convert my date ranges into days of the year then I can match the day of the year I was born against the ranges of days for star signs. I've used a switch statement to check against multiple conditions. Within a scriptblock I’ve asked if the value I’m passing is 'in' the array of dates for each star sign. The match will return the star sign and is held in the $starSign variable.

The Final part of the process block is to work out how many days until your next birthday. By capturing the current date, formatting the date of birth by removing the year born, adding the current year and finally subtract the amended date of birth against the current date. Phew!
This will leave a number of days until your next birthday. The 'if' statement is added if your birthday has already happened at the time of the code, it simply reverses the sum to give a positive number.

The end block displays the three captured results to the host.

I hope you have enjoyed this post and can see the many options possible for dates in PowerShell.
Feel free to download the script from my GitHub https://github.com/Gbeer7/Get-Age.git

function Get-age {
    param( 
        [Parameter(Mandatory=$true,
                   HelpMessage="Date must be written as dd/mm/yy",
                   Position=0)]
        [ValidatePattern("^(0[1-9]|[12]\d|3[01])/(0[1-9]|1[0-2])/(\d{2})$")]
        [string]$Bday    
    )

Begin {
    # use 'get-date' to convert '$Bday' Variable
    $cDate = (get-date -Date $Bday)

    # from today's date subtract birth date
    $diff = (Get-Date).Subtract($cDate)
}

Process {

    # Work out Years, months and days
    [int]$daysInYear = '365'
    [int]$averageMonth = '30'
      
    # years
    $totalYears = [math]::Truncate( $($diff.Days) / $daysInYear ) 
    
    
    $totalMonths = [math]::Truncate( $($diff.Days) % $daysInYear / $averageMonth ) 
    
    # days
    $remainingDays = [math]::Truncate( $($diff.Days) % $daysInYear % $averageMonth ) 

    # Your star sign
    $thisYear = (get-date).Year
     
    $starSign = 
    switch ($cDate.DayOfYear) {
    
        { $_ -in @( ((get-date 22/12/$thisYear).DayOfYear)..365; 0..((get-date 19/01/$thisYear).DayOfYear) ) } { "Capricorn" }
        { $_ -in @( ((get-date 20/01/$thisYear).DayOfYear)..((get-date 18/02/$thisYear).DayOfYear) ) } { "Aquarius" }
        { $_ -in @( ((get-date 19/02/$thisYear).DayOfYear)..((get-date 20/03/$thisYear).DayOfYear) ) } { "Pisces" }
        { $_ -in @( ((get-date 21/03/$thisYear).DayOfYear)..((get-date 19/04/$thisYear).DayOfYear) ) } { "Aries" }
        { $_ -in @( ((get-date 20/04/$thisYear).DayOfYear)..((get-date 20/05/$thisYear).DayOfYear) ) } { "Taurus" }
        { $_ -in @( ((get-date 21/05/$thisYear).DayOfYear)..((get-date 20/06/$thisYear).DayOfYear) ) } { "Gemini" }
        { $_ -in @( ((get-date 21/06/$thisYear).DayOfYear)..((get-date 22/07/$thisYear).DayOfYear) ) } { "Cancer" }
        { $_ -in @( ((get-date 23/07/$thisYear).DayOfYear)..((get-date 22/08/$thisYear).DayOfYear) ) } { "Leo" }
        { $_ -in @( ((get-date 23/08/$thisYear).DayOfYear)..((get-date 22/09/$thisYear).DayOfYear) ) } { "Virgo" }
        { $_ -in @( ((get-date 23/09/$thisYear).DayOfYear)..((get-date 22/10/$thisYear).DayOfYear) ) } { "Libra" }
        { $_ -in @( ((get-date 23/10/$thisYear).DayOfYear)..((get-date 21/11/$thisYear).DayOfYear) ) } { "Scorpio" }
        { $_ -in @( ((get-date 22/10/$thisYear).DayOfYear)..((get-date 21/12/$thisYear).DayOfYear) ) } { "Sagittarius" }
    } 
    
    # Work out how many days until birthday    
    $now = [DateTime]::Now   
    $dm = get-date $Bday -UFormat "%m/%d/" 
    $Days = [Datetime]($dm + $now.Year) – $Now

    # If birthday has happened this year change sum
    if (!($Days -ge 0)) { $Days = $now - [Datetime]($dm + $now.Year) }               
}
        
End {
    # display
    "`nYou are {0} year(s), {1} month(s) and {2} day(s)" -f $totalYears, $totalMonths, $remainingDays
    "Your Star sign is: " + $starSign
    
    # and...
    if ($cDate.Year -eq (get-date).Year) { 
        "You have another $($daysInYear - $diff.Days) days until your birthday" # If you are under 1 years old
    } else { 
        "You have another $($Days.days) days until your birthday" # over the age of 1 
    }
    
}

}# Function End

Every pithy witticism begins with quotation marks

"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:

PS> Delete-Item C:\tmp\foobar.txt
PS> Get-ChildItem *.log
PS> Get-Process svchost, conhost, powershell

It would certainly be cumbersome if you needed to quote each of those arguments, so PowerShell was designed well, in that respect.

But what if you ran the same commands just slightly differently?

PS> "C:\tmp\foobar.txt" | Delete-Item 
PS> "*.log" | Get-ChildItem 

Here you must use quotation marks or you will suffer the wrath of a terminating error from the PowerShell host most certainly!

Those are just a couple of the many examples I consider in When to Quote in PowerShell. Accompanying the full article, I also included a wallchart that condenses all the article's salient points into a single-page reference. Here's a fragment of the wallchart:

Guide to PowerShell Quoting wall chart

Read the article and download the wallchart here.

Practical PowerShell Unit-Testing

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.

... you wanted to know about Unit Testing in .NET | Coding in .NET

Making Awesome Dashboards from Windows Performance Counters

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?

Full Hyper-V Dashboard

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

 

 

Documenting your PowerShell API--solved!

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...

 

Sample Doc-Comments for PowerShell source

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:

csharp doc-comment sample

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:

doc wallchart thumbnail

Here's the link to get you started on this fun journey:

Unified Approach to Generating Documentation for PowerShell Cmdlets

Skip to toolbar