Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Thursday, September 3, 2015

PowerShell and Chocolatey Goodness

A movement has long been afoot to bring a useful package management system to Windows. If you’ve used apt or yum or yast or some similar tool in a Linux distribution, then you know how easy it can be to install new software to your computer with the right utility. Enter chocolatey, the PowerShell package manager for Windows.
Before starting a new class I make sure I load up my instructor computer with my favorite text editor and my chosen file manager:
choco install -y vim doublecmd
If I’m going to play videos for my class, I may also add a nice player:
choco install vlc
Of course, if I see that the machine I’m using has an older version of PowerShell I may want to update that:
choco install -y powershell4
What if I don’t know the name of the package I want? If I want to install the Angry IP network scan tool but know not what the package is called, I’ll ask chocolatey:
choco search angry
This is such a cool tool that rumor has it that even Microsoft is interested in using it. We’ll see. Perhaps managing software in Windows will soon be as easy as it is in Linux.
Bee seeing you.
​

Friday, August 21, 2015

PowerShell: Set Multiple Variables at Once

A list of variable names can be an l-value, that is, an expression that appears on the left side of an assignment operator. Did you know that you could do this…
PS C:\> $FirstName, $Initial, $LastName = 'John', 'Q', 'Public'
This statement will assign each variable the corresponding value on the right of the assignment operator. What if the number of variable names and values doesn’t match? Extra values will be stored as an array in the last variable, so in
PS C:\> $FirstName, $Initial, $LastName = 'John', 'Q', 'Public', 'Sr', 'Esq'
that $LastName variable will be a list containing Public, Sr, and Esq. If there aren’t enough values, the extra variable names are unassigned.
Oh, and if you want to set several variable names to the same value, use this:
PS C:\> $a = $b = $c = $d = 90
Have fun with your variables. Be seeing you.
​

Monday, August 17, 2015

PowerShell - Microsoft's Trident: Part 3, Scripting

PowerShell and Programming

I’ve been examining the three facets of PowerShell that make it such a powerful and useful tool in the hands of the Windows system admin. In this first post I talked about the shell and its ability to plumb the depths of .NET. In the second post I discussed what makes cmdlets so cool and why every kid should want one. In this post we round out our look with…

The Language of PowerShell

Yes, even though it is a shell environment and it has a passel of useful cmdlets, it is also a rich programming (well, scripting) language. If you’ve ever written code in Assembler, C, FORTRAN, BASIC, Java or the like, you can appreciate all the goodness that PowerShell as a language has to offer.

1. Functions

Code reuse is a term that gets tossed about in programming circles, but all that it means is to write and debug your code one time and use it over and over again. Not only does this prevent you from “re-inventing the wheel” but it makes your work easier to maintain. Once you know something works you just keep using it.
To that end PowerShell supports functions, blocks of PowerShell code that can be referred to by name. They look something like this:
function Say-Hello ([String] $Name = 'Anonymous') {
    Write-Host -NoNewLine 'Hello, '
    Write-Host -ForegroundColor Cyan -NoNewLine $Name
    Write-Host '.'
}
This creates a silly little function named Say-Hello that does just that, but in color. However, once we tweak this function to get it to work just the way we want it, all we have to do is call it:
Say-Hello Dave
Now we can drop this function call in anywhere we want to, as long as the function has been defined. Of course, if we want to use it in multiple scripts we really don’t want to have to copy and paste the function into all of them, so that brings us to…

2. Libraries

Libraries are files, PowerShell scripts, that generally contain nothing but definitions: variables and aliases sometimes, but mostly functions. When your script uses a library it can inherit all the names that were defined in that library. Libraries make it easy to write portable functions that may be used anywhere, and that’s what code reuse is all about.
PowerShell supports two different mechanisms for using libraries. You can load any PowerShell script into another using the dot operator to “source” the file, just like you can in UNIX shells:
. $HOME/myScriptsDir/myLibrary.ps1
Note the space after the dot, because it is a command.
If the library has been saved as a module, that is, with a .psm1 extension, it can be managed through PowerShell’s module system and loaded with a cmdlet:
Import-Module $HOME/myScriptsDir/myLibrary.psm1
Modules and dot-sourced scripts each have a place, but both allow you to create libraries of useful functions and easily use them over and over again.

3. Flow Control

Any programming or scripting language is arguably only as strong as its support for flow control, the ability to suddenly change direction at run time when the situation demands it. PowerShell has several tools for creating scripts that can respond to changing circumstances.
  • Comparison Operators
    PowerShell contains a fairly rich set of comparison operators and can perform all kinds of tests to see if certain conditions have been met.
  • Branching Constructs
    Sometimes you need a script to execute different instructions depending on some condition. PowerShell supports both if and switch keywords for branching to different parts of the script based on useful comparison results.
  • Iteration (a.k.a, Looping)
    PowerShell has five different looping constructs built in to the language, not to mention an iterative cmdlet. There are many ways to repeat tasks in PowerShell.

4. Exception Handling

One of the beauties of PowerShell is that is has not one, but two mechanisms for exception handling. The trap keyword creates global error handlers that can be used to create a default behavior should any part of your script throw an exception. The try..catch construct can deal with errors at very specific parts of your script, giving you the flexibility to handle the same error in different ways depending on where in the execution it occurs.
These can each be used alone or combined together in the same script. Each has its strengths and addresses slightly different challenges for dealing with errors, but both give you the tools to ensure that exceptions are caught and dealt with in your PowerShell scripts.

Really, PowerShell is a feature-rich language with first-class tools that allow you to write really useful administrative scripts. Of course, what would you expect from the company that brought BASIC to the Altair 8800?
Be seeing you.
​

Monday, August 3, 2015

PowerShell - Microsoft's Trident: Part 2, Cmdlets

The Second Point on the PowerShell Trident

In a previous post I began to look at the three aspects of PowerShell that make it so powerful. In that first article I examined the shell itself, and how it can be used to do some really cool things. Now for the second point…

Cmdlets (/kəˈmandlits/)

Cmdlets are wonderful things. As I stated in that last article, you can run just about any command in the PowerShell shell. But why would you? Between .NET (see that previous article) and the three-thousand-or-so cmdlets in PowerShell 3 and later, anything you need to do from the command line is taken care of.
Yes, initially there will be a bit of a learning curve, but it’s not nearly so bad as you might think, and the advantages far outweigh the inconvenience of learning something new. Besides, as a mentor of mine once said, “The day you stop learning is the day you start dying.” So let’s learn what makes cmdlets so cool.

1. They’re consistent.

If you’ve used any command line environment in the past—CP/M, UNIX, DOS—one source of endless frustration is the lack of consistency among all those commands. “Can you use a space here? Are parameters prefixed with a slash, a dash, two dashes, or not at all? Are they case sensitive?” The very fact that one must even ask such questions makes learning to use the command line difficult and contributes to it’s bad reputation.
But really, it’s foolish to expect anything else. Each of those commands was written by different people at different times to solve different problems. Their authors each had his own experiences and way of thinking that affected how he would address his particular need. It’s only natural that those commands bear little resemblance to one another.
But then came the GUI. When Apple introduced the Lisa in the early eighties it also published a style guide so that developers could write programs that correspond to the system’s look and feel. Microsoft did the same when Windows was released some years later. Building on that experience, Microsoft has provided some recommendations for developers of new cmdlets so that users don’t have to face the arduous task of learning a new set of commands from scratch. In theory, once you learn how to use one cmdlet you can apply that knowledge to any cmdlet. In practice, it works really well.

2. They’re well-documented.

Referring to those operating systems previously mentioned: help in CP/M was non-existent; in DOS it was terse and sometimes cryptic; and while often useful and informative in UNIX the man pages for commands are as diverse and inconsistent as the commands themselves. When a user has to toil by the sweat of his brow to unearth a little information, it’s little wonder that he would run the other way rather than learn how a command works.
PowerShell, though, is actually helpful. The Get-Help cmdlet provides different levels of verbosity, from printing out basic syntax to highlighting every detail of each argument that a cmdlet will accept. It can even display working examples of how a cmdlet is used, which fits my learning style perfectly. You can also search through the help using the standard shell wildcard characters * and ?.
And it’s thorough. Not only can you find information on cmdlets, but concepts are documented as well. Try Get-Help about_arithmetic_operators to find out how PowerShell does math, or Get-Help about_if to review how PowerShell makes decisions. If you need to know something about PowerShell, like Prego spaghetti sauce, “It’s in there.”

3. They return objects.

One of the things that makes it difficult to use command line tools is that they go about their business, perhaps print something on the screen, and leave. This is fine if you happen to be hanging about to read the output, but makes things tough if you want to automate some task in a script. The problem is one of parsing.
Let’s say that I want to fetch a computer’s IP address from DNS and use that address in some other process. I can use:
nslookup www.centriq.com
Since I can see the result on screen, I can parse the output, find the relevant data, and do what I want to with it. Humans are good at this sort of thing; computers, not so much. Let’s try to fetch just the IP address in cmd.exe with some fancier command-fu:
set host=www.centriq.com
for /f "usebackq tokens=2" %%i in (`nslookup %host%`) do set ipaddr=%%i
Now I have a variable called ipaddr that contains the IPv4 address of host, right? Well, maybe. The problem is that nslookup changes its output depending on the information in the DNS record it queries. This command expects the data of interest to be on the last line of output, which will work much of the time, but not always.
Compare that to the following:
$host = 'www.centriq.com'
$ipaddr = resolve-dnsname $host | ? ip4address | select -expand ip4address
If an A record for host exists, the ipaddr variable will always contain an IPv4 address. No doubt about it, and no parsing necessary. The object that PowerShell creates from the Resolve-DNSName cmdlet will have an IP address property that we can directly query and save in a variable.
In fact, all of those objects have useful properties and methods that we can use to customize the output of a cmdlet or even change the state of a computer. These objects can start services, kill processes, change passwords, and so on. They are infinitely more useful than a few lines of text output upon a computer screen.

If you’ve ever found the command line infuriating don’t let that stop you from learning how to get what you want from PowerShell. Its cmdlets were designed to address the very frustrations you’ve had with other shells. While learning this new system will require an investment of time and effort, the dividends are definitely worth it.
Stay tuned for part three of this series. Be seeing you.
​

Thursday, July 30, 2015

PowerShell(s) of Two

While writing out some IP addressing exercises I needed a quick reminder of some of the powers of 2 that I use a little less frequently. I just opened up a PowerShell console and made a little table like this:
foreach ($i in 0..32) {"{0,8} {1,-11}" -f $i, ([System.Math]::Pow(2, $i))}
Hope you find this useful. Be seeing you.
​

Tuesday, July 28, 2015

PowerShell - Microsoft's Trident: Part 1, the Shell

The Three Tines of PowerShell

Like the powerful trident in the hands of Poseidon, PowerShell can be wielded for good or ill. It can create vast wellsprings of new possibilities for the savvy administrator and unleash destructive floods of complexity on the uninitiated. To some it solves many problems, to others it is the source of many headaches.
What I want to examine now, though, is the triune nature of this beast. Like Poseidon’s legendary weapon, PowerShell takes a three-pronged poke at the issues that commonly beset us in IT.

The Shell

PowerShell is a shell. That is, it’s an environment in which you can type commands to get your computer to do something. But it’s a really cool shell.

1. It gives you direct access to .NET.

I can’t stress this enough. .NET. From the command line. At your fingertips at all times, ready to do your bidding. If there is anything you must know about PowerShell, it is this. Almost anything that can be done in .NET can be done from the command line in PowerShell. Do you want to get data from a web server?
[System.Net.WebRequest]::Create('http://www.mysite.com/index.html')
Do you want to place the cursor somewhere particular on the screen?
$Host.UI.RawUI.CursorPosition = @{x = 20; y = 47}
I’m talking about some cool stuff. For example, Microsoft failed to give us an equivalent to the DOS ‘pause’ command in the initial release of PowerShell, and their eventual addition of a comparable function is lame. That’s because PowerShell can’t respond when you “Press any key to continue…” It doesn’t know you’ve pressed a key until you hit Enter and send to it the contents of the keyboard buffer. But .NET can access the keyboard at a lower level, bypassing the buffer:
function Wait-Key {
<#
.SYNOPSIS
Prompts the user to press a key and waits until the user does so.
.DESCRIPTION
The Wait-Key function simulates the DOS program pause. It gives a script an
opportunity to wait for the user to press a key before proceeding.
.PARAMETER Message
The prompt message to display when the script pauses.
#>
        [CmdletBinding()] param (
            [string] $Message = "Press any key to continue..."
        )

        $Message
        $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") | Out-Null

}      # end function Wait-Key
With .NET and the MSDN website at your beck and call your command-fu is only limited by your imagination.

2. It allows you to run any command.*

From PowerShell you can launch any graphical program. Open up a text file in notepad or an html report in your default web browser.
notepad .\seating_chart.txt
Invoke-Expression ./disk_report.html
You can run any command-line utility…
ipconfig /displaydns
… even old CLI tools whose arcane syntax can cause PowerShell to balk—when you use the --% operator between the command and it’s arguments.
ICACLS.EXE --% C:\TEST /GRANT USERS:(F)
* Okay, so not really ANY command. You can’t run commands that are built in to the old CMD.EXE or COMMAND.COM command shells. This makes sense, as those commands are not stand-alone tools but are BUILT-IN. That’s why there’s point number 3.

3. PowerShell has cool aliases for useful commands.

As stated in the caveat above, CMD.EXE had several commands integrated into the shell itself. There are no executables for DIR or CD or DEL, so you can’t get at those from PowerShell. However, Microsoft has borrowed a page from other shells and given us aliases. While not quite as useful as the UNIX implementation of the concept they do allow us to create familiar or shortened names for common commands. So I can type DIR—or ls for that matter—and get a directory listing. Granted, what I get is not the result of DIR but the PowerShell Get-ChildItem command, so things are a little different, but not completely alien. I can easily create aliases of my own, if I like:
Set-Alias -Name unlink -Value Remove-Item
Set-Alias -Name goto -Value Set-Location
With aliases I can customize the shell to suit the way I prefer to work. To me, that makes PowerShell the best Windows shell around.

So stop using that old command interpreter. PowerShell is a much better shell than anything Microsoft has given us before, and with it we can do so much more than CMD will allow. And stay tuned for the other two prongs in the PowerShell trident.

Be seeing you.
​

Monday, August 11, 2014

Express Yourself, Regularly

The Basics of Regular Expressions

Introduction

Unix administrators have long used regular expressions to help them locate files, modify data, and manage system configurations. Tools like grep and sed are designed to process regular expressions to provide the administrator with exactly the information he wants. While versions of these tools have been ported to Windows, most Windows administrators are unaware that they exist. Because of the limitations of the Windows command shell, Windows administrators typically stick with slower, more complicated graphical tools to manage the operating system.
Enter PowerShell. PowerShell is designed to be a replacement for the standard Windows shell, and it is far more powerful and flexible than its predecessor. Among the many command enhancements PowerShell offers is built-in support for regular expressions. It borrows this capability heavily from Perl, a scripting language that was developed specifically for processing text.
Regular expressions are used to search for character sequences inside text strings or files. Programs that process regular expressions look for text that matches a given pattern. The components of a regular expression are not complicated, but the available combinations are many and varied, making it possible to perform some very sophisticated matches. Whether you’re administering Windows, Linux, or the Unix-based Mac OS X, you should invest some time learning the cryptic syntax of regular expressions so that you can manage systems and automate common tasks.
This tutorial will introduce regular expressions. It is not aimed at a particular operating system. Students of both Linux and PowerShell will come away with a basic knowledge of how regular expressions work and how to craft their own. Specific tools such as Linux’s grep command and PowerShell’s -match operator are covered in those respective classes at Centriq Training.

Overview

Whenever we begin to learn a new technology we get excited about the possibilities. We catch a glimpse of all kinds of nifty things that we can do with this knowledge. We often forget, though, that each technology has its limitations. Regular expressions are cool and powerful and flexible and a lot of other things, but there are some things that they’re not—some things that they cannot do. Like all things new, regular expressions come with a learning curve that is best overcome with practice. To avoid getting frustrated as you begin to learn regular expressions you must always keep three rules in mind.

Rule 1. Regular expressions match text, not numbers.

Regular expressions can represent any sequence of characters that you can find on a typical keyboard, and even some that you can’t, but they can’t express any other kind of data. They don’t understand numbers.
This confuses people at first, because regular expressions are frequently employed to determine things like whether a user’s input is a numeric age or zip code or year. But in these cases the regular expression is used to test the characters and ensure that they are numerals. The quantities that these numerals stand for are completely lost on the regular expression: it can’t identify a numeral’s value.
Remember, even numbers are written with characters. Regular expressions can be used to recognize those characters, but they can’t be used to determine their values, so they don’t work with actual numbers.

Rule 2. Regular expressions are made from three components: characters, anchors, and modifiers.

Every regular expression must have at least one character. This provides the basis for any match that will be performed. Anchors may be used to establish that the characters belong in certain positions in the text. Modifiers may be used to match repeated instances of a character or change a character’s meaning.
Characters are pretty simple, but the anchors and modifiers are what make regular expressions so powerful—and difficult to read. No matter how complex the expression, though, it always begins with at least one character.

Rule 3. Each program is a little different.

There are many programs and programming languages that can process regular expressions. While there is a standard definition of characters, anchors, and modifiers individual programs have sometimes extended and customized their definition of a regular expression. Generally, this is done to make expressions easier for us humans to use, but it can lead to confusion for the student who is just learning the syntax. In this tutorial I’m going to stick mostly with standard syntax, but at the end I’ll provide specific examples with grep and PowerShell.
So if you run across a regular expression that looks unusual or that doesn’t work in your specific tool, that doesn’t necessarily mean that it’s wrong. Each program is a little different.

A First Look at Characters

The group of characters that make up a regular expression’s search string is called a pattern. Patterns can be very simple. For example, d is a valid pattern. It matches any string of text that contains a “d” character, like “Dave”, “dude”, or “all work and no play makes Jack a dull boy”. Whether the matching is case-sensitive depends on the processor that’s performing the match. Remember Rule 3: each program is a little different.
When it comes to matching characters, you should know that most regular expression processors are going to match only the first instance that they find. In that last string, the expression matches the “d” in “and”, but not the one in “dull.” Once a program finds the first match, it usually stops processing the string altogether.
Characters can be combined to make whole words or phrases. The pattern error will match any string that contains the word “error” in any form. This includes “errors”, as well as other words like “terror”. Remember that the pattern you’re searching for is just a string of characters. If your pattern includes spaces or other special characters, you usually have to enclose it in quotation marks.
Sometimes we don’t want to match a particular character, just any character. For this we use a wildcard, which in regular expression syntax is a period. The pattern d.d would match “dad”, “dude”, and “katydid”, because there must be exactly one character between the two d’s. The pattern d...d will match “David”, “domed”, “android”, and even “my good buddy Steve” because in each case there are d’s separated by three characters. Note that in the last example those three characters include a space. That’s okay: a wildcard matches any character—even numerals, spaces, and punctuation marks.

Anchors Put It Where You Want It

An anchor is a special character that ties a part of your pattern to the beginning or end of a text string. The caret symbol, ^, can be created by pressing Shift-6 on most US keyboards. It anchors a pattern to the beginning of a search string. The pattern ^car will match “caret”, but not “lascar”. The caret symbol at the beginning of the pattern tells a regular expression processor that no character may precede the pattern.
The dollar symbol, $, can be created by pressing Shift-4 on most US keyboards. It anchors the pattern to the end of a text string. The pattern ave$ will match “Dave” but not “avenue”. The dollar symbol at the end of the pattern tells the regular expression processor that no character may follow the pattern.
A pattern that includes both anchors can be used to search for an exact match of the pattern to the text string. The pattern ^error$ will exactly match the string “error”, but not “terror” or “errors”. It will not match a string that contains the word “error” among other things, like “error in module fuse.ko”—it is always an exact match.
Of course, you can combine wildcards with anchors. The pattern ^d...d$ will match “David” and “dared”, but not “android” or “dreaded”. And if you want to match on a blank line, you can use the pattern ^$.

Expanding a Pattern With Modifiers

The Great Escape

You’ve learned that, in regular expression syntax, a period is a wildcard. But sometimes we want to search for a literal period. Because the period stands for any character, the pattern ^169.254. would match the IP address “169.254.14.2”, but it would also match the string “1698254a”, which is not what we’re looking for. What we want to do is modify the period and change its meaning.
The backslash character, \, is a special modifier called the “escape character”. It changes the meaning of the character that immediately follows it, “escaping” from the normal interpretation of the pattern. When it precedes a period, the backslash takes away the period’s meaning as a wildcard so that it becomes a normal period. So the pattern ^169\.254\. will match “169.254.14.2” but not “1698254a”. Since the periods have been “escaped”, there are no wildcards in this pattern. Likewise, the pattern ^\$ will look for a string that begins with a dollar sign, and ^4\^2$ will match a string that contains exactly “4^2”.

Time and Time Again

It is often necessary to look for a repeating number of characters in a text string. Multipliers allow you to extend your expression to include repetition in your searches. They are special characters that follow some other character in a pattern. They multiply the character that appears immediately before them by some value. There are several multipliers, so you’ll need to commit them to memory.
The question mark, ?, can be produced on most US keyboards by pressing Shift-/. It multiplies the preceding character by zero or one. The pattern ^d.?d$ will match both “dd” and “did”, requiring zero or one characters between the d’s.
The asterisk, *, can be produced on most US keyboards by pressing Shift-8. The asterisk multiplies the preceding character by zero or more. The pattern ^d.*d$ will match “dd”, “did”, “dreamed”, and “drumming in your head”, because it allows any number of characters to exist between the d’s.
The plus symbol, +, can be produced on most US keyboards by pressing Shift-=. It multiplies the preceding character by one or more. The pattern ^d.+d$ matches “did”, “dreamed”, and “drumming in your head”, but it does not match “dd”. The plus symbol requires at least one character to appear between the d’s.
Advanced multiplication is not supported by all regular expression processors, and not consistently among those that do. Remember, each program is a little different. However, because many programs and programming languages support it to some extent you should get to know it and its variations.
Advanced multipliers contain values inside curly braces, the { and } characters. These can be produced on most US keyboards by pressing Shift-[ and Shift-] respectively.
Placing a single value in the braces multiplies the preceding character by exactly that number. The pattern ^d.{3}d$ matches “David” and “druid”, requiring exactly three characters between the d’s. Note that this pattern could have been written ^d...d$, but as we learn about more characters we’ll see that the advanced multiplier can be much easier to read.
Enclosing two values separated by a comma within the braces, we get a specific range of multipliers. The pattern ^d.{3,5}d$ multiplies the wildcard by three, four, and five. It matches “druid”, “darned”, and “dreamed”, requiring three to five characters between the d’s.
If the braces contain a single number followed by a comma, the range of multipliers has no upper limit. The pattern ^d.{3,}d$ matches any string with three or more characters between the d’s.

Advanced Characters

There’s more to characters than literal symbols and wildcards. While the advanced characters may not look like single characters to you, to the regular expression processor they are indeed just a character. Sometimes these are called “meta-characters”, because they are a group of symbols that stand for a single character. Combined with multipliers, these meta-characters make it possible to create sophisticated searches.
Square brackets allow you to specify one from a group of characters that you want to match. The pattern ^d[aiu]d$ represents three characters. The symbols between the brackets are applied in turn to the search, so that this pattern matches “dad”, “did”, and “dud”. The pattern requires that there must be nothing but an a, i, or u between the d’s.
If you want to search for a string that begins with a vowel you can use the pattern ^[aeiou]. You can negate the pattern with a caret symbol inside the brackets. The pattern ^[^aeiou] matches all strings that begin with any character that is not a vowel. Don’t let the use of the caret confuse you. At the beginning of a pattern the caret is an anchor. Inside square brackets it reverses the meaning of the group. This could be read as “not a, e, i, o, or u”, so inside brackets the caret symbol means “not”.
The brackets can also contain a range, two values separated by a hyphen. The pattern [0-9] represents all numerals. The pattern ^169\.254\.[0-9]{1,3}\.[0-9]{1,3}$ uses escape sequences, ranges, and multipliers to match IP addresses that begin with “169.254.”.
Since a range of characters is just a character in regular expression syntax, ranges can be grouped. The pattern ^[0-9a-z] will match all strings that begin with a numeral or a lowercase letter. Many shell scripts use the pound sign at the beginning of a line to identify comments. The pattern ^[#a-zA-Z] matches all the lines in a script that begin with a pound sign or a letter.
Many common character groups have special classes defined for them. The range [0-9] can also be written using the class [:digit:]. Other classes include [:alpha:] for all letters, [:lower:] for lowercase letters, [:upper:] for uppercase letters, [:alnum:] for letters and numbers, [:space:] for white space characters like space and tab, [:cntrl:] for non-printable control characters, and [:xdigit:] for characters used to represent hexadecimal numbers, equivalent to [0-9a-fA-F].
Some advanced regular expression processors such as those found in Perl and PowerShell can also use escape sequences to represent character classes. Some common ones are: \d to represent any digit; \w to represent any word character such as letters, numbers, and some punctuation; and \s to represent white space characters. A capital letter in the escape sequence negates it, so \D represents any character that is not a digit, and \S represents any character that is not white space.
Parentheses, ( and ), can be produced on most US keyboards by pressing Shift-9 and Shift-0 respectively. They can be used to combine multiple patterns together. The pipe symbol, |, is produced by pressing Shift-\ on most US keyboards. It ties together multiple patterns within the parentheses using “or” logic. The expression (^[:digit:]{5}$ | ^[:digit:]{5}-[:digit:]{4}$) contains two patterns, and will process a string until one pattern or the other matches some text. This regular expression matches a US zip code written in either the five-digit or five-plus-four-digit format, such as “02134” and “64119-4105”.
Finally come the angle brackets, < and >, which can be produced on most US keyboards by pressing Shift-, and Shift-. respectively. These identify word boundaries, so whatever is enclosed within is considered to be a whole word. The pattern < error > matches “error”, but not “errors” or “terror”. The angle brackets require that only white space or punctuation may appear on either side of the enclosed pattern.
Please note that many regular expression processors will require that curly braces and angle brackets be preceded by a backslash to escape them, otherwise they are treated as literal brackets. You may have to experiment or read your program’s documentation to determine what it will support.

Summary

Regular expressions consist of character patterns that are matched against text strings. Each pattern must contain at least one character, but its matching capabilities can be enhanced with anchors, modifiers, and advanced meta-characters.
Regular expression patterns can be written to match almost any kind of text, but they don’t assign any meaning to that text. A regular expression recognizes no numeric values, it doesn’t understand what to do with punctuation marks, and it’s limited to matching on one line of a file at a time. All that the pattern can represent is text characters.
Regular expression processors are programs and programming language constructs that use patterns to find and work with text. Some of these have very advanced capabilities, such as extending a search to include multiple lines of a file or performing pattern matches backward as well as forward on the text. The beginner will need to practice with each of the regular expression tools that he intends to use to gain an understanding of its features, but the fundamental concepts covered in this tutorial will be applicable.
Regular expressions provide the administrator with tools to search for any kinds of text within files. They can be added to scripts to check for patterns within user input. They are often used to identify important information from log files, email servers, and web sites. Any process that works with text can be improved by the judicious use of regular expressions.

PowerShell Examples

When the PowerShell -match operator finds the pattern in a string it returns “True”. It returns “False” if the pattern is not found.
PS C:\> $value = "This is a test. 1234"
PS C:\> $value -match "a.t"
True
PS C:\> $value -match "^t"
True
Note that PowerShell is not case-sensitive.
PS C:\> $value -match "\st\w{3}"
True
PS C:\> $value -match "\d$"
True
PS C:\> $value -match "t[aeiou]s"
True
PS C:\> $value -match "t[^aeiou]s"
False
PS C:\> $value -match "\w+\. \d+$"
True
PS C:\> $value -match "\w+\. \d?$"
False
PS C:\> $value -match "(tisk | test)"
True

Grep Examples

The grep command is intended to work with files, so these examples pass a test string to the command through standard input. The command returns the string that matches the pattern, or null if there is no match.
$ value="This is a test. 1234"
$ echo $value | egrep a.t
This is a test. 1234
$ echo $value | egrep ^t
$ echo $value | egrep -i ^t
This is a test. 1234
Note that grep is case-sensitive. Use the -i parameter switch to enable case-insensitive matches.
$ echo $value | egrep [[:space:]]t[[:alpha:]]\{3\}
This is a test. 1234
With grep, character classes must be quoted or contained within square brackets. The double-bracket form is the most common. Note that curly braces must be escaped.
$ echo $value | egrep [[:digit:]]$
This is a test. 1234
$ echo $value | egrep t[aeiou]s
This is a test. 1234
$ echo $value | egrep t[^aeiou]s
$ echo $value | egrep '[[:alpha:]]+\. [[:digit:]]+$'
This is a test. 1234
$ echo $value | egrep '[[:alpha:]]+\. [[:digit:]]?$'
$ echo $value | egrep '(tisk | test)'
This is a test. 1234
$ echo $value | egrep '\'
This is a test. 1234
​