Photo by JJ Ying on Unsplash.com

Photo by JJ Ying on Unsplash.com

Regular expressions and metacharacters in PowerShell

Patterns

Article from ADMIN 42/2017
By , By
Almost all programming and scripting languages allow the use of regular expressions, but many professionals still believe regex is a relic from ancient times. With specific examples, we show how useful and meaningful regex can be in PowerShell.

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

...
Use Express-Checkout link below to read the full article (PDF).

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy ADMIN Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus
Subscribe to our ADMIN Newsletters
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs



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.

Learn More”>
	</a>

<hr>		    
			</div>
		    		</div>

		<div class=