Five more PowerShell tips in five minutes!

Nathan Magyar
4 min readNov 30, 2020
Picture of a macbook air with Visual Studio Code (VSCode) in the background showing script being written. Commes Des Garcons.
The more you can learn about PowerShell the better.

After receiving a surprisingly positive response (thank you!) to my first PowerShell tips article — Level Up your Powershell with five tips in five minutes!, I’ve decided to release another short article with five more. If you haven’t read my first article, be sure to check it out.

  1. Use splatting to de-spaghettify your code!
    Splatting is a great way to transform potentially messy or long lines of code into a beautiful easy to read format. How does it work? PowerShell associates each value in the collection you specify with a valid command parameter. Splatting variables are just like standard variables, except that they begin with an At @ instead of a dollar sign $. The At symbol tells PowerShell that you are passing a collection of values, instead of a single value.

This is a very easy one to implement in your scripting activities. Instead of writing out:

Set-ADUser -Identity "Mark" -SamAccountName "MarkJones" -Office "Melbourne" -Manager "John" -EmployeeID "1234" -UserPrincipalName "MarkJones@medium.com"

Try splitting it out into a nice, easy to read format using splatting.

$SetSplat = @{     
Identity = "Mark"
SamAccountName = "MarkJones"
Office = "Melbourne"
Manager = "John"
EmployeeID = "1234"
UserPrincipalName = "MarkJones@medium.com"
}
Set-ADUser @SetSplat

Simple, effective and easy to read. Incorporate splatting into your scripts today!

2. Turn your nifty little one-liners into powerful functions
If you’re anything like me, you’ve probably written hundreds of one-liners that you recycle and re-use on a regular basis. With PowerShell Functions you can turn those tidbits of code into functions and call on them whenever you need! To write a function simply type ‘function Function-Name’ then, open a curly brace, put your script body in and close your script block with a closing curly brace.

function Example-Function {
SCRIPT BODY HERE
}

An example of a function I wrote can be found below. This one utilises a parameter — don’t worry if you don’t know what that is, I’ll cover that in my third tip! This function creates a very basic HTML report of the memory usage on your Hyper-V host.

function Get-VMMemoryReport {
param(
[Parameter(Mandatory=$True,HelpMessage="Provide report path", ValueFromPipeline = $true)]
[string]$Path
)
Get-Vm | forEach ($_.Name) {Get-VMMemory $_.Name} | ConvertTo-HTML -Property VMName,DynamicMemoryEnabled,@{label=’MinimumSize(MB)’;expression={$_.minimum/1mb –as [int]}},@{label=’StartupSize(MB)’;expression={$_.startup/1mb –as [int]}},@{label=’MaximumSize(MB)’;expression={$_.maximum/1mb –as [int]}}> "$path\SimpleMemoryReport.html"}
The more you know!

3. Use parameters!
Using the parameter I defined in my prior tip, I’ll quickly break down how they work at a high level. If you want to do more reading on parameters, take a look at this.

Now, let’s break down that parameter! Firstly, we’ll take a look at the syntax of a parameter. A parameter is simply defined by the below:

param (
$parameterName
)

We’d call this a named parameter. What this means is that if you were to call this script and specify -ParameterName ‘Test’ as an argument, the variable $parameterName would then be filled with the string ‘Test’. This can then be called later on in the script.

In the case of the function in tip two; we’ve added a few more arguments:
Mandatory=$True — This enforces the use of this parameter, if you call the script/function without specifying this argument it will fail to run.
HelpMessage — This allows you to specify a help message for your argument.
ValueFromPipeline=$True — This allows the argument to accept input from the pipeline.

With all of these in place, our parameter will look like this:

param(
[Parameter(Mandatory=$True,HelpMessage="Provide report path", ValueFromPipeline = $true)]
[string]$Path
)

This turns a simple, named parameter into a powerful, required parameter with it’s own help message that accepts pipeline input. You can apply this to almost anything, just swap out the help message and $path variables for something more suited to your script!

4. Do { use PowerShell } While (Career -eq IT)

Do.. While loops are a great tool that can be used to ensure a specific criteria is met before proceeding to the next part of your script. They can also be leveraged to ensure that your script does not continue on for longer than intended. Ed Wilson of Microsoft has an excellent write up on this, which can be found here. I’ve created a quick example of a do.. While loop as below — this split the users in your domain in two and assign half of them to a UAT group.

$number = (Get-ADUser -Filter *).Count/2
do {
$user = Get-ADUser | Get-Random | Where {$_.MemberOf -NotLike "UAT"}
Add-ADGroupMember -Identity "UAT" -Members $user
$count++
} while ($count -lt $number)

5. Don’t hard code your scripts!

This is a big one. Common sense, but a big one nonetheless. Avoid hardcoding your script, unless it is highly practical to do so. One way around this is using variables in tandem with the Read-Host -Prompt cmdlet / argument. Using this allows you to run your script, targeting different principals everytime with the nuts and bolts inside remaining the same. An example could be:

$server = Read-Host -Prompt "Please enter the server name here"Invoke-Command -ComputerName $server -ScriptBlock {
SCRIPT BLOCK HERE
}

I’ve added the function I listed in this script, along with a couple other Hyper-V functions and the do.. While example to my GitHub repository. It can be found below. Enjoy!

--

--

Nathan Magyar

A Systems Engineer with a passion for all things PowerShell based in Melbourne, Australia. https://www.linkedin.com/in/nathanmagyar/