
Photo by JJ Ying on Unsplash.com
Regular expressions and metacharacters in PowerShell
Patterns
When administrators worked exclusively at the command line, they could impress the ordinary user with the endless rows of cryptic letter and number combinations (e.g., (\d{1,4}\.){4}(\d{1,4})
), which then changed entries in text files as if by magic.
Even though system administrators today do a large part of their work with graphical tools that provide a convenient interface, the use of regular expressions (regex) significantly facilitates the work. This is true, in particular, when you need to automate and simplify tasks with the use of PowerShell scripts.
PowerShell with Regex
If you have already developed or used some PowerShell scripts, you will typically have come into contact with regular expressions – even if you were perhaps not aware of it. The following example illustrates this very well:
$An_Array = @('somethingno1', 'somethingno2','morestuff') $An_Array | Where-Object {$_ -match 'something'}
Here, you first create an array of strings and then launch a query that only displays the first two elements of the array, because the third element does not match the 'something'
pattern. The -match
operator can also be used without the Where-Object
cmdlet. Thus, calling:
'somethingno1' -match 'something'
returns the value True because the search pattern was found in the string, whereas calling:
'somethingno1' -match 'nothing'
logically returns False
. The -replace
operator also works with regular expressions such as
'The book is good' -replace 'The book', 'The ITA book'
which then returns the string The ITA book is good
. The -replace
operator compares, finds the matching string The book
, and replaces it with the The ITA book
before output. Thus, the
Buy this article as PDF
(incl. VAT)
Buy ADMIN Magazine
Subscribe to our ADMIN Newsletters
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Most Popular
Support Our Work
ADMIN content is made possible with support from readers like you. Please consider contributing when you've found an article to be beneficial.
