Tips and Tricks

Tips and Tricks
msorens
PowerShell for Admins

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:

msorens
PowerShell for Admins

Complete Guide to PowerShell Punctuation

Quick as you can, can you explain what each of these different parentheses-, brace-, and bracket-laden expressions does?

${save-items} ${C:tmp.txt} $($x=1;$y=2;$x;$y) (1,2,3 -join '*') (8 + 4)/2 $hashTable.ContainsKey($x) @(1) @{abc='hello'} {param($color="red"); "color=$color"} $hash['blue'] [Regex]::Escape($x) [int]"5.2" When you’re reading someone else’s PowerShell code, you will come across many of these constructs, and more. And you know how challenging it can be to search for punctuation on the web (symbolhound.com not withstanding) !
That is why I put together a reference chart containing all of PowerShell’s symbology on one page. making it much easier when you need to look up a PowerShell symbol as you read code–or to browse for the right construct when you are writing code.
PowerShell Punctuation wall chart
Download the Complete Guide to PowerShell Punctuation wallchart from here.

Matthew Hodgkins
DevOps

5 Tips for Writing DSC Resources in PowerShell 5

PowerShell 5 brought class based DSC Resources, which majorly simplifies the process of writing custom DSC resources.
During my time working on some custom resources, I developed some tips a long the way which should save you some time and pain during your DSC journey.
The tips cover:

  • Structuring your class based DSC Resources
  • Making it easier to get IntelliSense based on your DSC resources without constantly copying them into the module path
  • Using PowerShell ISE IntelliSense when writing DSC configuration
  • Troubleshooting resources which aren’t being exposed correctly from your DSC Module
  • Testing classed based resources with Pester

Head over to https://hodgkins.io/five-tips-for-writing-dsc-resources-in-powershell-version-5 to take a look at the tips.

msorens
PowerShell for Admins

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

Tim Curwick
Tips and Tricks

Getting complex – More line breaks in Powershell

This is a follow up to Jacob Moran’s article Keeping it simple - Line breaks in PowerShell.
I am strongly in the pro backtick camp, but I won’t get into that debate here. Instead, I’ll cover more of the common ground between the two camps.
In addition to after a pipe, there are many, many more places where you can put in a line break without a backtick and without breaking your code.
As a rule of thumb, any spot where the syntax unambiguously must be followed by something more, you can break the line.
As an extreme example, this:

msorens
PowerShell for Admins

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

Steve Parankewich
PowerShell for Admins

Convert VBA Macros To PowerShell for Microsoft Office Automation

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.

Steve Parankewich
DevOps

Connect to all Office 365 Services with PowerShell

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.

Matthew Hodgkins
DevOps

Using PowerShell to enable ChatOps on Windows

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:

Steve Parankewich
DevOps

Create Windows Shortcuts or Favorites With PowerShell

Creating windows shortcuts are usually done through the New Shortcut Wizard, MSI files, Group Policy Objects, or even a simple file copy. Shortcut files are .lnk files that Microsoft Windows uses for shortcuts to local files while .url is used for destinations such as web sites. As we all are aware, the .lnk filename extension is hidden in Windows Explorer even when “Hide extensions for known file types” is unchecked in File Type options. The reason for this is the NeverShowExt string value in HKEY_CLASSES_ROOT\lnkfile. Shortcuts are also displayed with a curled arrow overlay icon. The IsShortcut string value causes the arrow to be displayed.
For a full run down on creating shortcuts and favorites with PowerShell head over to PowerShellBlogger.com.