How to Check if a String Contains Special Characters in PowerShell

Check if a string contains special characters in PowerShell

Need to check if a string contains special characters in PowerShell? Use -match with a negated character class. It returns True as soon as one character that isn’t a letter or digit shows up: The catch is deciding what “special” means. Spaces, underscores and accented letters like é all change the answer, and the -like … Read more

How to Join and Concatenate Strings in PowerShell (-join, +, -f)

Join and concatenate strings in PowerShell with the -join operator

To join strings in PowerShell, put the -join operator between a list and the separator you want. For two or three values, double quotes or the + operator concatenate them just as well, and -f builds a string from a template: Output: Those four cover nearly every case. The details below matter when the list … Read more

How to Remove Whitespace from Strings in PowerShell

Remove whitespace from strings in PowerShell

To remove whitespace from strings in PowerShell, use .Trim() for spaces at the start and end, or -replace ‘\s’, ” to strip every space, tab and line break: Which one you need depends on whether the spaces inside the text matter. I tested every example in PowerShell 7 and Windows PowerShell 5.1, including the invisible … Read more

How to Add a New Line in a PowerShell String

Add a new line in a PowerShell string

To add a new line in a PowerShell string, put `n (backtick n) inside a double-quoted string. The text after it starts on the next line: Output: That covers most scripts. Below I show the other new line options, when each one matters, and how to turn spaces into new lines. I ran every example … Read more

How to Check if an Array Is Empty in PowerShell

Check if an array is empty in PowerShell

To check if an array is empty in PowerShell, test its Count property. An empty array has a Count of 0, and so does a variable that holds $null: The traps are $null on the wrong side, one-item arrays that look empty, and objects with no Count in Windows PowerShell 5.1. I’ll show where PowerShell … Read more

PowerShell Where-Object Between Two Dates (With Examples)

PowerShell Where-Object between two dates

To filter objects between two dates with PowerShell Where-Object, compare the date property against a start and an end date and join both tests with -and: That one line hides three traps: times of day on the end date, dates that are really strings, and slow filtering on big logs. I’ll walk through each with … Read more