Introduction to windows powershell

Introduction to Windows PowerShell. Windows PowerShell is an advanced command environment that Microsoft has installed in Windows to provide the user with the ability to control, manage, and configure Windows services as a shell. In this article, we will fully explain Windows PowerShell and tell you the difference between PowerShell and CMD. Stay with us.

Table of Contents

In today’s world, people dealing with Windows must be familiar with the CMD or Command Prompt environment.
Command Prompt or CMD is a simple text environment that supports very few commands alone and has been on Windows since the birth of Windows NT.

Command Prompt uses two sets of commands that include:

Internal Commands: Internal commands are located inside the Command.com file. Like the dir command

External commands: commands that have a separate file and can be executed and controlled in the Command Prompt environment. Like the netsh command

Now, with the short description that we have provided to you about CMD and the fact that this grammatical environment is more than 20 years old, it can be realized that it no longer has the necessary capabilities and efficiency for users, especially professionals in the field of executing commands.

So in 2006, Microsoft launched a new command environment called Windows PowerShell to improve the quality of its Windows command environment.

Microsoft outlined the reasons for the development and release of Windows PowerShell, two of which were the most prominent.

Introduction to Windows PowerShell.

The main reasons for the production and development of Windows PowerShell

1. Creating a complete text environment for running, controlling and managing all services and launching them.

2. Do not lag behind Linux due to the very high power of the Linux terminal.

The Linux terminal environment is very powerful and it can be said that all the various tasks including controlling and running all services can be done with Linux commands. For this reason, in order not to lag behind Linux, Microsoft started producing and developing an environment called Windows PowerShell, so that it can provide its users with the ability to work with a text environment more than before.

The difference between Windows PowerShell and CMD

One of the main differences between these two Windows command text environments is the undisputed power of Windows PowerShell.

Network administrators, programmers, and professional Windows users will be able to run and manage any services and commands they have in the Windows graphical environment in PowerShell.

The CMD grammatical text environment has the limited ability to execute commands.

In Windows PowerShell you will be able to write and execute professional scripts such as nested scripts and multi-step scripts.

The Command prompt environment supports limited commands and there is no ability to add commands as a module.

In Windows PowerShell you will be able to add modules to new and external services and control and manage them.

The structure of Windows PowerShell

Windows PowerShell with the help of .net framework Designed and developed. For this reason, writing and executing commands in it is similar to the .net programming language. Users can also use the C# and .net commands as scripts in PowerShell.

For example, a simple command in PowerShell is as follows:

New-NetIPAddress –InterfaceAlias “Ethernet” –IPv4Address “192.168.0.1” –PrefixLength 24 -DefaultGateway 192.168.0.254

In the example above, a static IP will be set on the system.

Tip for working with PowerShell

At first, when you come across PowerShell commands, you might think that you have to memorize a lot of commands for that long. But we have to tell you that this is not true.

Windows PowerShell follows certain rules and regulations that make it very easy. Also, working with Command Prompt commands may seem difficult at first, but with a little effort and perseverance, you can be sure that you will easily learn PowerShell.

How to open Windows PowerShell

There are three different ways to open Windows PowerShell.

1. Press Winkey + R to open Run, then enter powershell and click OK.

2. From the Start menu, search for windows powershell and open it.

3. In CMD environment, by entering powershell and pressing Enter, you will go to PowerShell environment.

Finally, we will mention some of the benefits and features of PowerShell.

Benefits and Features of Windows PowerShell

Ability to execute all CMD commands in PowerShell

Being object oriented

Ability to write scripts with net language and PowerShell script language

Structured commands

Ability to increase different modules

Manage and control all Windows server and client services

Existence of PowerShell ISE tool for easier scripting

Ability to execute multi-step and selective commands

Ability to enter commands automatically after entering part of the command

Has system control commands to improve and expedite the needs of the user

Ability to execute commands remotely

Ability to direct PowerShell to control servers (in Windows 10 family)

Dear user, we hope you would enjoy this tutorial, you can ask questions about this training in the comments section, or to solve other problems in the field of Eldernode training, refer to the Ask page section and raise your problem in it as soon as possible. Make time for other users and experts to answer your questions.

Introduction to Windows PowerShell.

Goodluck.

Contents

  • Introduction
  • What is PowerShell and Why is it Useful?
  • Getting Started
    • Open PowerShell
    • Navigation
      • Viewing Directory Contents with Get-ChildItem (gci, ls)
      • Moving Between Directories with Set-Location (sl, cd)
      • Creating New Directories with mkdir
      • Using Explorer to View Directories in the GUI
      • Deletion with Remove-Item (rm)
      • Understanding the Tree Structure of Your Computer’s File System
      • Moving fast with Push-Location (pushd) and Pop-Location (popd)
    • Working With Files
      • Creating Files with New-Item (ni)
      • Copying and Moving Files with Copy-Item (cp) and Move-Item (mv)
  • Doing More
    • Writing to Files with Write-Output (write, echo) and Redirection
    • Reading Files with Get-Content (gc, cat)
    • Working with Lots of Files at Once Using Wildcards (*)
    • Searching with Select-String (sls)
    • Infinite Loops and Aborting with control-c
    • Specifying cmdlets with Parameters
    • Finding out more with Get-Help
    • Solving the Infinite Loop Problem with the -exclude Parameter
    • Getting Even More out of cmdlets with Piping
    • Using Command-Line Tools and Running Python Scripts
  • Conclusion
  • Quick Reference

This tutorial will introduce you to the basics of Windows PowerShell, the standard command-line interface for Windows computers. If you are a Mac or Linux user, you should check out the Bash introduction instead. If you are already familiar with using Bash, you may be able to get started with PowerShell just by looking at the table at the end of this lesson.

The tutorial is divided into two main sections. In the first section, “Getting Started,” you will learn to do basic desktop tasks like creating and opening files and folders using PowerShell. In the second section, “Doing More,” you will get a glimpse of some of the features that make work on the command line particularly efficient, and learn enough of the basics to be able to explore further on your own. You will also get set up to run Python scripts from the command line.

This tutorial was written for PowerShell 5.0. If you are using an earlier version, you may encounter a few small syntax differences which you should be able to overcome with a little help from a search engine.

What is PowerShell and Why is it Useful?

Windows PowerShell is a command-line interface for Windows computers. A command-line interface (CLI) is a program for telling your computer to do tasks using typed commands, rather than by clicking pictures on the desktop as in a graphical user interface (GUI). (Technically, PowerShell is more than just the CLI, and you can get a quick overview of its features on Wikipedia.) Using the command line has many advantages. It makes it possible to automate tasks and to do many things with one command. Most importantly, a number of tools of value to humanists can only be run from the command line, including many you can learn about on The Programming Historian, like Mallet, Pandoc, or Wget. The command line is also the best place to work with programs you have custom built for your own research using programming languages like Python.

Getting Started

You will first learn to navigate through your files and do some of the basic tasks you do every day on the computer.

Open PowerShell

Run a search for PowerShell on your computer. You probably have several different options, like “PowerShell,” “PowerShell ISE,” and “PowerShell (x86).” The ISE (integrated scripting environment) is a handy tool which allows you to write scripts on the fly, and also has a convenient look-up for all the PowerShell commands. Right now, this is more than we need. “x86” exists for backwards compatibility. (If you’ve been around a while, you’ll remember old Intel processors from the 80s and early 90s called “286,” “386,” “486,” and so forth. That’s what “x86” is getting at. It is a 32-bit version.) We want 64-bit and simple, so we’ll use the one just called “Windows PowerShell.” You may want to pin it to your task-bar (right click it to get this option). When you open it, it will look like this:

PowerShell on start up

PowerShell on start up

If you don’t like the white on blue, right click the top bar, select “properties,” and go to “colors” to change things. You may have to close and re-open PowerShell to get it to display correctly.

Navigation

A nice thing about PowerShell is you always know where you are because it tells you in the prompt. In my case, I see:

C:\Users\Ted>

You should see something similar, but with your user name. In case you don’t, type

sl ~

Make sure to include the space. This will bring you to your home directory: C:\Users\YOURUSERNAME where “YOURUSERNAME” is replaced with the name of your account on the machine. “Directory” is just another word for “folder,” and PowerShell considers your user folder — not the desktop — to be your home. (The desktop is actually just another folder within your user folder, that is, a subdirectory of the user directory). Entering sl ~ is just like opening the folder called “Users” and from there “YOURUSERNAME” using your GUI. Let’s start by learning how to move around between directories and view their contents.

Viewing Directory Contents with Get-ChildItem (gci, ls)

Our first command is Get-ChildItem. Go ahead and type it in, and hit enter. You’ll see a list of everything in your current directory. In my case, that looks like this:

Listing directory contents with `Get-ChildItem`

Listing directory contents with Get-ChildItem

Notice that I didn’t actually enter Get-ChildItem. I just entered gci. The commands we will be learning are all of the form Verb-Noun. These are called “cmdlets” (pronounced “commandlets”), and their form is supposed to make it easy to remember what they do and predict similar cmdlets. Because cmdlets are rather long, most of them come with sleeker aliases that you can use instead. I will first present cmdlets with their names, but always subsequently use the standard aliases, because they are much faster to work with. It is important to note that many cmdlets have multiple aliases. For instance, Get-ChildItem, gci, dir, and ls all do exactly the same thing. While it is unsurprising that gci is short for Get-ChildItem, you may be wondering where dir and ls come from.

PowerShell is relatively new (first released in 2006), and its designers anticipated that many people who would use it would already have experience with some existing CLIs (command-line interfaces), specifically either with Microsoft’s older CLI called command prompt, or with Linux CLIs like Bash, which is now also standard on OS X. Thus, many cmdlets have an alias that is the standard command in one of these two systems (and often for both). In the present example, dir comes from command prompt, and ls comes from Bash. I will use the “PowerShell-style” aliases in this tutorial, since it makes it easier to remember the actual cmdlet names. However, I will try to also mention other common aliases, particulary those familiar to Bash users. If you work with a lot of people who use OS X or Linux, it can be good to know these names. The table at bottom gives the cmdlets along with their standard PowerShell aliases and the nearest Bash equivalent.

Go ahead and try using gci, dir, and ls. You’ll get the exact same list of things. Most of these things will be directories. One of them should be your desktop. Let’s move into that directory.

Moving Between Directories with Set-Location (sl, cd)

To move to your desktop, we’ll use the Set-Location cmdlet. Enter

sl desktop

into PowerShell. This tells PowerShell to move to the desktop. Notice that you can write “desktop” using all lowercase letters, even though when you looked at the contents of the YOURUSERNAME directory, “Desktop” was spelled with a capital “D”. PowerShell is not case sensitive! Now that you’ve changed your location, you can use gci to see a list of everything on your desktop — that is, everything in the directory named Desktop. If you’re as disorganized as I am, this will be a long list. We can move back to the YOURUSERNAME directory by typing

sl ..

Don’t leave out the space! Now type

sl ..

again. You should be in the Users directory.

Now try navigating back to the desktop, and then back again to Users. That should take four commands: sl YOURUSERNAME, sl desktop, sl .., sl ... But you can actually do it with only two. You should be at C:\Users> right now. Instead of typing sl YOURUSERNAME and then sl desktop, you can just type

sl YOURUSERNAME\desktop

and get to the desktop with one command! Similarly, from the desktop, by typing

sl ..\..

you can get back to where you started with one command. If you don’t have the pinkie stamina for typing \ all the time, you can also type sl ../... Not only is PowerShell not case sensitive, it also doesn’t care what direction the slash goes. sl ../.., SL ..\.., Set-Location ..\.., and set-location ../.. all do exactly the same thing.

Creating New Directories with mkdir

We’re moving toward working with files. Before we start, let’s make a directory where we can store everything we’re using for this lesson. Navigate back home by typing

sl ~

We’ll make a new directory inside of your YOURUSERNAME directory. To do this, we use the command mkdir. Call your directory whatever you want, but try not to use spaces, as these make working on the command line more complicated than necessary. I will call my directory “funWithPowerShell”. So I type

mkdir funWithPowerShell

See how I used CamelCase to avoid spaces? Another common way to do this is with hyphens or underscores, as in fun_with_power_shell. Whatever you name your directory, try to avoid using spaces. Once you’ve been working with PowerShell a little, you’ll probably find that you start titling new files without spaces by default. This is a good habit to be in, as it simplifies work on the command line as well as work with programming languages like Python.

However, you probably have plenty of existing files with spaces in their names. To open these in PowerShell, you just need to use quotes. Let’s try this. Move into your new directory using

sl funWithPowerShell

(Or whatever you titled your directory.) Enter

gci

and you’ll see that there’s nothing here. That’s because you haven’t put anything in it! Let’s put a new directory inside with mkdir. We’ll call this directory “Directory with a long name and lots of spaces”. Because the name has spaces in it, we’ll have to use quotes to create it. Type

mkdir "Directory with a long name and lots of spaces"

and hit enter. Now enter

gci

and you’ll see your new directory. Suppose we want to move into this directory. We would have to type sl "Directory with a long name and lots of spaces". Not only will this take a while to type, but if we get one letter wrong, PowerShell won’t be able to find our directory. Instead, try just typing

sl d and then hitting the tab key.

Voila! PowerShell completes the name of the directory for us, including the quotes! Using tab for auto-completion will save you a lot of time. You’ll notice that when PowerShell completed the name for us, it also threw in a .\ at the beginning of the directory name. The dot is just shorthand for the current directory. When you type commands, PowerShell always assumes there’s a .\ at the beginning — in other words, that you are referring to something in the current directory. So you don’t have to type this part (unless you want PowerShell to look somewhere else for whatever you’re telling it to do, in which case you can type the path for that directory — i.e. C:\directory\bla\etc.)

Let’s practice a little more with directories before getting to files.

Using Explorer to View Directories in the GUI

At this point, we’ve made two directories. I mentioned above that “directory” is just another word for “folder.” You can see this for yourself by finding your new directories in the GUI. Windows actually calls your GUI “File Explorer” or just “Explorer.” We can call Explorer from within PowerShell by using the command Explorer. Navigate back into your funWithPowerShell folder with

sl ..

Now try typing

explorer .

Remember, the dot just means “this directory,” and you don’t have to capitalize “explorer” because case doesn’t matter in PowerShell. Explorer should have just opened a window showing the contents of the “funWithPowerShell” directory. Arrange your windows so you can see both the image in Explorer and PowerShell. Now you’ll be able to watch how what you do in PowerShell shows up in Explorer.

The Explorer command is extremely useful. It is essentially like double-clicking something in the GUI. Thus, you can also use it to open files and programs.

Deletion with Remove-Item (rm)

Now that you can see the results of what you’re doing in PowerShell, let’s learn to delete things — for instance that directory with the long name. First, create a few more directories. Name them “dir,” “dir1,” and “dir2.” You can make all three with a single command by typing

mkdir dir, dir1, dir2

Pretty neat, huh? You should see your three new directories pop up in your open Explorer window.

Now, let’s get rid of that long-named directory. To do this, we use the cmdlet Remove-Item or just rm. You have to be very careful with this cmdlet, because it does not put things in your recycle bin. It deletes them permanently. Gone. Type in rm followed by a space and the long-named directory’s name. You’ll probably want to use tab for auto-completion. Note, however, that now that we have a bunch of directories with names beginning with “d”, so we have to type through the first unique letter to get it to auto-complete correctly. So I type

rm dire and then hit tab.

Alternatively, you can just type rm and then hit tab multiple times to scroll through all your directories. If you go too far, use shift with tab to scroll back.

Before pressing enter, I stare long and hard to make sure I’m deleting the thing I want to delete. Then I hit enter.

Go ahead and delete the other three directories, and watch them disappear from Explorer. Just like with mkdir, you can delete all three directories with one command. Give it a try.

We just deleted the dir, dir1, and dir2 directories. But we’ll need them for the next example. So let’s create them again. Rather than typing out the instruction, though, try just tapping the up arrow on your keyboard a couple of times. You should soon see the command you used to make the three directories the first time. Once you do, hit enter, and they’ll be made again! Like using tab to auto-complete, using the up and down arrows to scroll through recent commands will save you a lot of time! Note that we are not undoing our earlier deletion. We are just using a shortcut to enter again a command we’ve recently used.

Understanding the Tree Structure of Your Computer’s File System

Okay, now you should have three directories inside your funWithPowerShell directory. Move into the dir directory. (Use sl dir).

It’s important to understand how your computer organizes things. Look at the path to your current directory. The path is all the stuff written before the >. In my case, that’s

C:\Users\Ted\funWithPowerShell\dir

Yours should look pretty similar. What this path actually represents is a tree-like structure the computer follows to get to where you are. The trunk of the tree is C: which is your hard drive. (Actually, on most modern computers, it will be a partition of your hard drive. Why is it called C? Your computer assigns a letter to every drive. A and B are reserved for the two floppy disk drives which long ago users would have interacted with more frequently than their hard drives. Even though most computers no longer have them, their names are still reserved.)

If C: is the trunk, each section of the path after it is a branch, each one coming off the one above it. Thus, Users is a branch from C:, Ted is a smaller branch coming off of Users and so forth. You could also use a metaphor of heredity rather than botany and call each branch a child of the directory above it. This is actually the more common language for describing the relationships between directories (hence the cmdlet Get-ChildItem), but we’ll stick with the tree metaphor, since in real life, relationships of heredity can be much more complex than the extremely hierarchical structure according to which your computer is organized.

Understanding that the path works like a tree is important for navigating around to directories not immediately above or below the current one. Thus, we know there is a directory called “dir1”, and that this directory is also in the “funWithPowerShell” directory. See what happens if you attempt to use sl to move directly over into it by typing

sl dir1

This threw an error!

An error caused by jumping between branches

An error caused by jumping between branches

We’ve tried to jump from one branch to another, and PowerShell can only understand our movement if we move along the tree. That means we first have to move up to where the branches for “dir1” and “dir” meet, and then back down to “dir1.” You can do this with one command. See if you can figure it out before you read the next line.

The command is:

sl ..\dir1

This tells PowerShell to move up one directory to funWithPowerShell and then move back down into the directory dir1.

Moving fast with Push-Location (pushd) and Pop-Location (popd)

Before moving on to working with files, let’s try out the commands pushd and popd. Do this: Go all the way up to the trunk of your tree, C:. That should be four directories above where you are, so you could type

sl ..\..\..\..

Then, change back to dir1. But rather than typing sl before the path, type pushd. Like this:

pushd users\YOURUSERNAME\funWithPowerShell\dir1

You’ll now be in the directory, just as if you’d typed sl at the beginning of that path. But here’s the fun part. Now type

popd

and hit enter. Neat, right? The command pushd tells powershell to move into the given directory after marking the current directory so it can be returned to with popd. In other words, popd will always “pop” you back to the last directory you were in before using pushd. (If you want to understand more about what is going on, read about the call stack on Wikipedia.) Using pushd and popd is very useful when you’re frequently moving between two directories.

Working With Files

Now that you know how to move around your computer’s file system from the command line, let’s work on actually doing things to files. We’ll start by learning to create new files, copy them, and move them around.

Creating Files with New-Item (ni)

First, we need some files to work with. Let’s make a new plain text document called “example.txt”. Navigate to the funWithPowerShell directory — use tab for each directory name as you type out the path to speed this up — and type

ni example.txt

then hit enter. Now do

gci

to see that, indeed, you now have, in addition to your directories, the file example.txt. We’ll need several files, so go ahead and make example1.txt and example2.txt. You’ll be unsurprised to hear that with a comma, you can do this in one command:

ni example1.txt, example2.txt

Copying and Moving Files with Copy-Item (cp) and Move-Item (mv)

We probably should have put these files into one of our directories. Let’s move them.

We’ll put example.txt in dir by typing

mv example.txt dir

Now type gci and you’ll see example.txt has disappeared. Move into dir (sl dir) and type gci and you’ll see it’s now in there! (You can also do this without moving by just typing gci dir from funWithPowerShell.) Move back to funWithPowerShell and put example1.txt in dir1 and example2.txt in dir2.

We can also use mv to rename things. Use sl to move into dir. Do a quick gci and you should see your example.txt file. This is a boring name. Let’s call it “benjamin.txt” instead. Type

mv example.txt benjamin.txt

Use gci again to confirm that your document is now called benjamin.txt.

You may be surprised that the same cmdlet is used both to move and to rename files. In fact, though, the operation is the same. In both cases, you’re telling the computer to change the “name” of the file’s location, that is, to change the path it follows to find the file. In the first example above, the path began as

C:\Users\Ted\funWithPowerShell\example.txt

and changed to

C:\Users\Ted\funWithPowerShell\dir\example.txt

In the second example, the path changed from

C:\Users\Ted\funWithPowerShell\dir\example.txt

to

C:\Users\Ted\funWithPowerShell\dir\benjamin.txt

In other words, in both examples, mv just changed the path. Don’t worry if this doesn’t make sense just yet. Just be careful when you use mv, because if you don’t type exactly the right thing, you may rename something when you mean to move it, or vice versa.

Beyond moving files, we also want to be able to copy and delete them. To copy files, we use the cmdlet Copy-Item, or cp. Let’s make a two copies of benjamin.txt, and name them “steven.txt” and “susie.txt”.

cp benjamin.txt steven.txt

cp benjamin.txt susie.txt

We can also delete these two new files with rm, just like with directories. Try to do it with one command. As always, be careful when you use rm.

Here’s the command:

rm steven.txt, susie.txt

Goodbye, Steven and Susie!

Moving, copying, and deleting

Moving, copying, and deleting

Doing More

Okay, so now we can navigate around, make files, and move and delete them in PowerShell. We feel pretty cool and/or geeky, because we can do these things from the command line, but it’s not actually useful, since we could already do these things pretty easily in the GUI. Now that we know these basics, though, we can start learning slightly more complex commands that can be useful in our work as digital humanists.

Writing to Files with Write-Output (write, echo) and Redirection

We have an empty file in our dir directory. That’s not very interesting. Let’s add some content. We could open the file in Notepad and modify it that way. But we can also add to it with commands right from the command line. The cmdlet we use for this is Write-Output, or just write.

Try entering this:

write "The technique of reproduction detaches the reproduced object from the domain of tradition."

PowerShell should print that statement directly into the command-line window. That’s all that write does. It tells PowerShell “Print out whatever I write.” That’s not very useful, though, because we want it to put this text into our document. To do this, we’ll use something called redirection.

Redirection is just a way to tell PowerShell to take the results of a command and put them somewhere other than in the PowerShell window. To redirect a command, we put a right angle bracket (>) between the command and the place we want its output to go. In this case, we want the output of our write command to wind up in benjamin.txt. So we use the up arrow to get the statement back, and add > benjamin.txt at the end. The whole thing should look like this:

write "The technique of reproduction detaches the reproduced object from the domain of tradition." > benjamin.txt

When you hit enter, nothing will seem to have happened. That’s because your write statement was redirected. To see that something did indeed happen, use gci to view the contents of your directory. Notice that the length of benjamin.txt is no longer 0. That’s because we just put some text in there!

Reading Files with Get-Content (gc, cat)

While gci can show us that something is in the file, it would be nice to see that it’s the sentence we tried to put in there. We could do this by typing notepad benjamin.txt, which would open the document in Notepad. But there is also a cmdlet for just printing the contents to PowerShell. This cmdlet is called Get-Content. Enter:

gc benjamin.txt

There’s your sentence!

Using gc by itself is helpful, but not that interesting. By combining it with redirection, we can do a lot more. For starters, we can put the contents of one file into another. This is a lot like copying a file. You already know how to do this with cp. Make a copy of benjamin.txt named benjamin1.txt using cp. That command will look like this:

cp benjamin.txt benjamin1.txt

Now, try to make benjamin2.txt, with the exact same contents as benjamin.txt but by using gc and redirection. See if you can figure out how to do this.

In case you’re stumped, here’s the answer:

gc benjamin.txt > benjamin2.txt

Of course, that’s just a more cumbersome way to do what we can already do with cp. The difference in these methods is substantial, though, because using gc we can append information to a text without replacing what is already there, and we can also get the contents of multiple texts and put them into another text.

First, let’s look at appending. We need something to append, so let’s make a new text called next.txt and write to it the sentence “By making many reproductions it substitutes a plurality of copies for a unique existence.” We could make our file first with ni, but we don’t need to. If we tell PowerShell to write to a file that isn’t there, it will make the file for us. Thus we can just enter

write "By making many reproductions it substitutes a plurality of copies for a unique existence." > next.txt

Use gc to check that next.txt really is what we want it to be.

Now, let’s add the content of next.txt to benjamin.txt using gc and redirection. Seems simple enough, right? Try entering

gc next.txt > benjamin.txt

Then, check what happened with gc benjamin.txt. You will see that you have indeed put the content of next.txt into benjamin.txt, but that you’ve replaced the content that was already there. This isn’t what we wanted to do!

Using >, we just told PowerShell to put the content of one text into another, and it overwrote what was already there. We can fix this by using >> for our redirection instead of just a single >. This tells PowerShell to append the new information. Try this:

gc next.txt >> benjamin1.txt

Use gc to see that benjamin1.txt now has both sentences.

The difference between ` data-lazy-src=

The difference between > and >>

Now, let’s see about getting the contents of multiple files at the same time.

Working with Lots of Files at Once Using Wildcards (*)

You should now have four files in your directory, each with one or two sentences from Walter Benjamin’s artwork essay in it. You might be losing track of what exactly is in them. Let’s use gc to check the contents.

We could look at each one individually. As you may have guessed, though, you can display all four with one command. Enter

gc benjamin.txt, benjamin1.txt, benjamin2.txt, next.txt

and you’ll get your sentence printed out three times. We can do this even more quickly. Try entering

gc *.txt

The result will be exactly the same thing. What the *.txt does is tell PowerShell to find anything ending with .txt. The * is called a wildcard, and can be used to replace any part of a file name. Try typing gc ben*, and you’ll get only the texts that begin with “ben”. Since the only files in this directory are the four we want, you can even type gc * and get the content we’re interested in by having PowerShell get the content of everything in the directory.

Searching with Select-String (sls)

Of course, we don’t always want to see everything. Often, we want to find specific content. Using *, we can search multiple files at the same time. One of our sentences had something about “unique existence,” didn’t it? Where was that? We can use the Select-String cmdlet to search for specific bits of text. Enter

sls "unique existence" *.txt

and PowerShell will spit out all the lines containing that string from any file in our directory ending in .txt.

Using sls on files as small as ours won’t save us all that much time over reading the files ourselves. But using this cmdlet with larger numbers of longer files can be extraordinarily helpful.

Infinite Loops and Aborting with control-c

Let’s look at one more useful task we can accomplish by combining gc, wildcards, and redirection. Suppose we have numerous different files we want to combine together into another file, for instance because we’ve downloaded hundreds of song lyrics we want to analyze, and want to group all the ones by a certain artist into a single file. Although we could do this by listing them all out, i.e. gc text1, text2, text3 > newtext, if we have a hundred texts, this will be pretty cumbersome. This is what wildcards are for.

Let’s try concatenating all four of our texts and putting the result into a fifth text. Using *.txt might seem a handy helper. We are about to do something foolish, so please read the next paragraph before typing this command!

Let’s try

gc *.txt > bigben.txt

Your computer will appear to do nothing. But unlike other times when your computer has apparently done nothing, this time, the command prompt doesn’t come back up. If you try to type another command, nothing will happen. This is because PowerShell is still working on your last command. As you do more and more complicated things with PowerShell, this will sometimes happen — you’re making your computer sweat! In this case, however, PowerShell will never stop working on this command, because it is in an infinite loop! Fortunately, you can abort this task with

control-c

Using control-c like this is very handy, as you may sometimes accidentally get caught in a loop, or you may just get sick of waiting for your computer to do certain extremely long tasks.

How did we just get stuck in that loop? We told PowerShell to put all files ending in .txt into a new file ending in .txt. Since that new file fell under the rubric of files the computer should be concatenating and adding to bigben.txt, it added that one in there, too. And then, since it had a .txt file with new content, it added that as well. This is a great example of something we often forget about our computers: they are not smart. Extremely powerful, yes. But totally lacking common sense. Humans look at instructions and try to interpret them. “She can’t possibly mean for me to add the contents of the final text back into itself over and over again forever.” Computers, on the other hand, do exactly what we tell them to, no matter how illogical our commands may be. As you gain experience working on the command line, you will often be flummoxed by your computer’s overly literal interpretations of your commands, but you will also learn how to give it instructions it can follow. Infinite loops should be avoided at all costs, but they will occur, and when they do, just remember control-c.

Specifying cmdlets with Parameters

We have seen that your computer needs to have things told to it in very exact ways. Fortunately, PowerShell provides methods for refining cmdlets by adding parameters.

Let’s look at an example. Use gci and you should see that you have five files in your directory. One of them, bigben.txt, is very large. Enter

gc bigben.txt

PowerShell will start dumping an inordinate amount of text onto the screen. You may want to abort the process with control-c (this is not an infinite loop, just a really large file, so you can wait for the whole thing to print, it’ll just take a while.) You can use the cmdlet clear if the large block of text bothers you.

What we really want to see is just that bigben.txt really is comprised of the lines of the other texts, repeated over and over again. We can do this by looking only at the beginning and ending, and for this, we add a parameter to our cmdlet.

Enter this:

gc bigben.txt -totalcount 10

You will see the first 10 lines of your text. Make sure to include the hyphen, as otherwise PowerShell will not know that -TotalCount is a parameter. Now enter

gc bigben.txt -tail 10

and you will see the last 10 lines. What we have done is specified our gc cmdlet with the parameters -totalcount and -tail. Almost all cmdlets can be refined by adding parameters like this. But how do we know what parameters are available?

Finding out more with Get-Help

PowerShell does not expect you to memorize all the possible parameters for all the cmdlets. Instead, it provides an easy way to list them off using the cmdlet Get-Help. Enter

Get-Help gc

and you’ll get a screen that looks like this:

Help page for `Get-Content`

Help page for Get-Content

Your page may be slightly different, but the important part to look at right now is the section labeled “SYNTAX.” This shows us all of the parameters we can add to Get-Content. If you’re just trying to remember the exact name of a parameter you’ve used before, this will be enough to jog your memory. But it doesn’t tell us what the parameters actually do.

Fortunately, Get-Help itself has parameters, and by adding -online to your Get-Help cmdlet, you tell PowerShell to ask your browser to open a page on Microsoft’s TechNet portal that explains all the parameters in plain English. Enter

Get-Help gc -online

The online help page for `Get-Content`

The online help page for Get-Content

Here we can see the actual description of the parameters -TotalCount and -Tail.

Solving the Infinite Loop Problem with the -exclude Parameter

Look again at the help for Get-Content, and you’ll see that one of the possible parameters is -exclude. This sounds promising for dealing with our infinite loop problem! The description online reads: “Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as ‘*.txt’. Wildcards are permitted.” This sounds very promising. The “Path parameter” is (usually) the thing you write immediately after your cmdlet. It tells PowerShell where to apply the cmdlet. When we type gc benjamin.txt, benjamin.txt is the path. It is actually shorthand for .\benjamin.txt, which in turn is shorthand for C:\Users\YOURUSERNAME\funWithPowerShell\dir\benjamin.txt. That line tells your computer the path to follow through the tree-like structure of your file system in order to find the file you want. What help is telling us, then, is that we can omit specified items from our gc cmdlet by adding the parameter -exclude and then entering the path we want it to exclude. We can use this to take the contents of all of our .txt files and put them into a new file without creating an infinite loop. See if you can figure out what to type, using what we did with -totalcount and -tail as a reference.

Here’s what I did. I first deleted my current bigben.txt with rm. (This isn’t really necessary, since using a single > on my redirect will replace the current contents anyway, but it’s nice to have a clean start!) Then I entered

gc *.txt -exclude bigben.txt > bigben.txt

Voila!

Throughout this process, we’ve been adding texts together, or concatenating them. You can learn more about concatenation from Wikipedia, and if you want to see a few more examples of concatenation using PowerShell, check out this blog entry, which will take you into the wonderful world of variables, something beyond the scope of this tutorial, but well worth learning about.

Getting Even More out of cmdlets with Piping

So now we have five documents in our directory. In order to be able to do really useful things with them, we need one more tool: Piping. Piping is sort of like redirection, but instead of telling PowerShell to put the results of a cmdlet somewhere else, it tells it to take the output of one cmdlet and use it as the input for another. Where we use > for redirection, for piping we use |.

We are going to get even more mileage out of gc, this time by piping its results to the cmdlet measure-object (or just measure). This latter cmdlet measures various properties. For our purposes, we will use it to get the number of lines, words, and characters in our files by adding the parameters -line, -word, and -character, or just -l, -w, -c. (With parameters, you only need to type as much of the name as necessary to identify the parameter in question. Use Get-Help to figure out what that will be for a given cmdlet.)

Enter this:

gc benjamin.txt | measure -l -w -c

You should get a count of the lines, words, and characters in the text. Of course, you could do this easily enough with your word processor. The power of working on the command-line comes from being able to manipulate lots of things at once and being able to specify what we want done with extra precision. In this example, this means we can count words in multiple of our files at once, and that we can add additional parameters to specify exactly how we want to count them.

See if you can get a count for the lines, words, and characters in all the files. It should be no surprise to you that the wildcard (*) can help you here. For instance, you could enter

gc *.txt | measure -l -w -c

With our five small files, this still doesn’t result in much, but it would have taken longer using the word processor, and we could also do it with a directory containing thousands of lengthy files. We can also control our actions more precisely with additional parameters. Use Get-Help measure to see the parameters at your disposal. We could go to the online help to learn more about them, but for now let’s just use one that’s self-explanatory as an example: -IgnoreWhiteSpace.

Use the up-arrow to get your last command back, and add -ignorewhitespace to the end. (You can also just type -ig, but -i alone is not sufficient, because it doesn’t differentiate the -IgnoreWhiteSpace parameter from the -InputObject parameter, as a helpful error message will tell you if you try it.) You’ll see the same count, but with fewer characters, because this time PowerShell didn’t count the spaces. The advantage of precision is clear over using a word processor, where it is difficult to determine whether or not white space is being ignored in the first place, let alone to toggle the feature.

The most important reason to become familiar with using the command line is not because of the increased precision or the ability to work with multiple files, useful as these features are, but rather because of the many additional tools you gain access to, as mentioned in the introduction. When getting set up to work with some of these tools, you may run into problems because Windows sometimes configures the paths incorrectly. Fixing this problem requires setting environment variables, a topic beyond the scope of this tutorial. Fortunately, there is a lot of support out there, and a little searching will usually turn up the solution you need. Because many lessons on The Programming Historian require you to use Python, let’s look briefly at getting Python set up. Having done this, you will be less daunted by instructions for setting environment variables for other programs.

If you don’t already have Python, or if you wonder why you would want to use it, check out the Python tutorial right here on The Programming Historian. In that tutorial, you will learn to set up Python to run scripts directly in an editor. It will often be more useful to be able to run scripts from the command line. In order to do that, we need to set an environment variable. First, you need to know the name of the directory where Python is installed on your computer. Enter sl C:\ and then use gci. You should see a directory named “Python” with the version number at the end. On my computer, the directory is “Python27.” Now we tell Windows to create a Path variable pointing to that directory by entering this into PowerShell, replacing “Python27” with the name of the directory on your computer:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")

This tells Windows: “Hey, the path for Python is C:\Python27.” If you want to understand exactly how this works, look at this page on Microsoft’s TechNet portal (the same portal you get to using the -online parameter with Get-Help).

Once you’ve entered the command above, exit PowerShell and start it again. You should now be able to start the Python interpreter by typing python into PowerShell. To run scripts, you simply type python followed by the path for the script you want. It’s easiest to first navigate to the directory with the script in it, and then just enter python script-name.py.

Now you’re all set up to run Python scripts from the command line!

Conclusion

In this tutorial, you’ve learned some of the basics of working with PowerShell, the command-line interface on Windows. You now know enough to use PowerShell for many of the day-to-day tasks you do on your computer, and I would recommend using it for just that. At first, you may find it more difficult to copy a file and move it to a new directory from the command line, but the more you practice, the more natural it will become. Eventually, you will be very comfortable working in PowerShell, and will be able to do many tasks more easily this way.

Although we have only had a glimpse of what PowerShell can do, you now have enough basic knowledge to learn to do more. There are lots of helpful resources online, and they are yours for the googling! It is also helpful to know that a lot of discussions about using the command line will be based on Unix and other *nix systems. In most cases, if you just type the names of the commands they are using together with “PowerShell” into a search engine, you will find the corresponding PowerShell cmdlet.

The more you use PowerShell, the easier it will be, and the more you will learn to unlock capabilities you did not even know your computer had! Eventually, you will see how constraining your GUI has been. You won’t stop using it, but you will find yourself starting up PowerShell more and more often to break free from these constraints, and utilize your computer more fully. Your computer is like a pocket knife. The GUI only allows you to open a few blades. With the command line, you can open them all!

Quick Reference

This table serves as a quick reference to all the cmdlets discussed in this lesson. The first column shows the actual name; the second shows what you will normally type instead. The Bash equivalent shows the most similar command in Bash. Unless this command is in parentheses, it can also be used in PowerShell as an alias for the corresponding cmdlet. (Linux and OS X users, please see the note below.) For a more complete explanation of any of the cmdlets, use Get-Help with the -online parameter (e.g. Get-Help Get-ChildItem -online.)

Cmdlet Alias Bash Equivalent Description
Get-ChildItem gci ls List the directories and files in the current location.
Set-Location sl cd Change to the directory at the given path. Typing .. rather than a path will move up one directory.
Push-Location pushd pushd Changes to the directory.
Pop-Location popd popd Changes back to the previous directory after using pushd
New-Item ni (touch) Creates a new item. Used with no parameter, the item is by default a file. Using mkdir is a shortcut for including the parameter -ItemType dir.
mkdir none mkdir Creates a new directory. (See New-Item.)
Explorer none (open) Open something using File Explorer (the GUI)
Remove-Item rm rm Deletes something. Permanently!
Move-Item mv mv Moves something. Takes two arguments — first a filename (i.e. its present path), then a path for its new location (including the name it should have there). By not changing the path, it can be used to rename files.
Copy-Item cp cp Copies a file to a new location. Takes same arguments as move, but keeps the original file in its location.
Write-Output write echo Outputs whatever you type. Use redirection to output to a file. Redirection with >> will add to the file, rather than overwriting contents.
Get-Content gc cat Gets the contents of a file and prints it to the screen. Adding the parameter -TotalCount followed by a number x prints only the first x lines. Adding the parameter -Tail followed by a number x prints only the final x lines.
Select-String sls (grep) Searches for specific content.
Measure-Object measure (wc) Gets statistical information about an object. Use Get-Content and pipe the output to Measure-Object with the parameters -line, -word, and -character to get word count information.
> none > Redirection. Puts the output of the command to the left of > into a file to the right of >.
| none | Piping. Takes the output of the command to the left and uses it as the input for the command to the right.
Get-Help none man Gets the help file for a cmdlet. Adding the parameter -online opens the help page on TechNet.
exit none exit Exits PowerShell

Remember the keyboard shortcuts of tab for auto-completion and the up and down arrows to scroll through recent commands. These shortcuts can save a lot of typing!

A note to Linux and OS X users: Although many Bash commands work in PowerShell, they often don’t do exactly the same thing. They may take different parameters, and the syntax may be slightly different. (Technically, they never do the same thing, as PowerShell commands produce objects, whereas Bash commands produce text.) However, the similarity of their actions offers a handy crutch for quickly getting up and running with PowerShell, and a little help from the Get-Help cmdlet (you can just type man like in Bash) will usually resolve any confusion.

In 2006, Windows Script Host (WSH) and the Command Prompt shell got a new sibling when Microsoft released a completely new environment called Windows PowerShell. PowerShell has some similarities to the older tools: Like the Command Prompt shell, it lets you type commands interactively as well as put them into script/batch files, and you can easily use pipes and redirection to string files and programs together. Like WSH, it provides a powerful object-oriented programming language for complex scripting.

But PowerShell is a very different, strange animal, and it has powerful features that go way beyond what WSH and the Command Prompt offer. I show you what I mean in the following sections.

An Object-Oriented Command Shell

Here’s one way that that PowerShell is different and strange. Recall that if you type dir into a regular Command Prompt window, the dir command spits out a bunch of text onto the screen, giving the names, sizes, and timestamps of the files in a directory. You can direct that text into a file using the > redirection operator, or you can “pipe” the text to another program using the | operator. For example, the command

dir /s /b | sort

lists the files in the current directory and its subdirectories as a stream of text, and the text is sent to the sort program that sorts them alphabetically. If you’ve used a command-line environment in nearly any computer operating system in the last, say, 30 years, this should be familiar.

Windows PowerShell command lines appear to work in the same way, but its commands deal with objects rather than just text — objects that represent files, folders, Windows device drivers, network services, documents any of the hundreds of objects defined in the .NET Framework library). What flows from one command to the next, via that pipe symbol (|), is a stream of objects. The various PowerShell commands let you generate, manipulate, invoke methods on, change properties of, and extract information from these objects.

As an example, here’s what happens when you type dir in a PowerShell window. The PowerShell dir command is actually an alias (shorthand) for the Get-ChildItem cmdlet. You can type either name and get the same result.

Wait, cmd-what? Cmdlet, pronounced “command-let,” as in “cute tiny little command.” PowerShell’s built-in commands are called cmdlets. Maybe they were out of vowels up in Redmond that year? No, the reason for the odd name is that they’re not completely built in to PowerShell, like cmd.exe’s commands, nor are they really completely independent of it, like exe files. They’re implemented in a new way, so they needed a new word. In any case. . .

With no other arguments, Get-ChildItem emits File and Folder objects for all the files and subfolders in the current directory. If I type the command dir with no arguments, Get-ChildItem spits out a list of File and Folder objects, and because there is no pipe or output redirection, the results spill into the Windows PowerShell command window.

When objects land in the PowerShell window, PowerShell prints one line for each object, in a nice columnar format, listing the most important properties of each object. For File and Folder objects, this includes the Name, Length, LastWriteTime, and Mode properties. The resulting list looks like this:

Directory: C:usersbknittel
Mode LastWriteTime Length Name
---- ------------- ------ ----
d-r-- 6/2/2010 1:27 PM Contacts
d-r-- 6/15/2010 11:35 PM Desktop
d-r-- 6/14/2010 8:47 AM Documents
d-r-- 6/2/2010 1:27 PM Downloads
:
d-r-- 6/2/2010 1:27 PM Videos
d-r-- 6/23/2010 11:01 AM Virtual Machines
-a--- 8/21/2009 6:07 PM 1889 listprops.vbs
-a--- 8/20/2009 12:34 PM 1020 nets.vbs
-a--- 8/20/2009 11:54 AM 3668 tempfile.txt
-a--- 9/14/2009 7:13 PM 1605 test.vbs
-a--- 6/23/2010 2:19 PM 3650 x

The headings at the top of the columns are just the names of the properties that are being displayed. The listing would be similar for any other type of object a cmdlet generated.

The thing to ponder here is that the dir command in the regular Command Prompt environment generates text in a fixed format. The dir cmdlet in Windows PowerShell generates a list of File and Folder objects, which PowerShell formats into a text listing after the fact.

You can redirect the output of a PowerShell cmdlet to a file, using the familiar > character, and the same thing occurs: the stream of objects gets formatted into a nice, text listing.

The innovation in PowerShell is what happens when you use the pipe redirection symbol (|). PowerShell lets you direct a stream of objects from one cmdlet to another, and they can change the properties of and call methods on these objects, doing real work as they get passed along. It’s only when the objects finally hit the screen that text appears. One cmdlet might generate a list of objects representing files, computers, services, and network objects; the next in the pipeline might filter and pass on just the ones that are of interest; and the next might call methods to perform actions on the objects. This is a truly unique feature of Windows PowerShell.

So, to do what used to require a loop in WSH:

fso = CreateObject(“Scripting.FileSystemObject”)
for each file in fso.GetFolder(“c:temp”).Files
   file.Delete
next

you can do with a single command line in Windows PowerShell:

dir c:temp | remove-item

dir generates a list of File and Folder objects representing the contents of directory c:temp and passes it to the remove-item command, which deletes the “real world” thing behind any object it’s passed.

You could also type the following:

(dir c:temp).delete()

which generates the same stream of File and Folder objects and calls the delete method on each object. The result is the same: The files are deleted.

(And, as you might expect, you could also just type remove-item c:temp*.*. That would be the most straightforward command, but it doesn’t show how PowerShell differs from the regular command prompt.)

Here’s another example of how a pipeline command can work:

dir | where-object {$_.LastWriteTime -lt
(get-date).addmonths(-6)} | remove-item

dir generates an object for each file in the current directory, where-object passes along only those that are more than six months old and remove-item deletes the old files. So, we’ve constructed a disk cleanup command out of general-purpose cmdlets. (Don’t type this command, by the way—it’s just an example!)

This is very peculiar and powerful, and it takes some getting used to.

An Extensible Environment

PowerShell can run three sorts of programs: built-in commands, external programs, and scripts. This is analogous to the regular Command Prompt environment, where you could use the built-in commands that are handled by the cmd.exe program itself, run external programs, or create batch files that let you orchestrate either type of command to perform the steps of a more complex task. In PowerShell, the built-in commands are cmdlets. Unlike the Command Prompt shell, however, these built-in commands are not wired into the PowerShell program but are added to it through a snap-in mechanism as one or more .DLL files stored on your hard disk. So, custom cmdlets can be added to the environment. The idea is that Microsoft and third parties can add install management cmdlets for their applications and servers, so that they can be managed by PowerShell scripts. Microsoft SQL Server, Microsoft Exchange, and VMWare servers have custom cmdlet snap-ins, for example. If you’re a skilled .NET programmer, you can create your own custom cmdlets using the Windows PowerShell 2.0 Software Development Kit (SDK) and Microsoft Visual Studio Express Edition, both of which you can download free from Microsoft.

In addition, PowerShell responds to command keywords that are part of its built-in script programming language which is a unique language, all its own. It’s not VBScript, it’s not VB.NET, it’s not C#. It’s PowerShell.

You can also create and use .NET and COM objects not just in scripts, as you do with WSH, but right at the PowerShell command prompt.

This means that every cmdlet, Windows program, command-line program, .NET object, and COM object (including WMI and ASDI) is available right at your fingertips.

Note – As an aside, it’s interesting to know that just as VBA provided an object-oriented, full-scale programming language that could be integrated into applications such as Microsoft Word, programmers can “host” PowerShell inside their .NET applications. PowerShell is intended not just for helping you automate your routine tasks, but to serve as the scripting/macro language for Windows applications and services.

Obtaining Windows PowerShell

Windows PowerShell 2.0 is installed by default on Windows 7 and Windows Server 2008 R2. For information on installing it on other versions of Windows, see PowerShell details on the Microsoft Web site.

The PowerShell Environment

You should be able to click Start, All Programs, Accessories and see Windows PowerShell as a choice (although you might have to scroll down; by default, it’s below System Tools). On 32-bit Windows versions, there are normally two choices:

  • Windows PowerShell—This is the interactive command-line environment. I discuss this first.
  • Windows PowerShell ISE—This is a GUI editing/debugging tool that you can use to help develop PowerShell scripts. I discuss this later.

On 64-bit versions of Windows, these two menu selections run the 64-bit version of Windows PowerShell. In addition, there are selections for Windows PowerShell (x86) and Windows PowerShell ISE (x86), which run the 32-bit versions of PowerShell. These are provided in case you have to use a cmdlet snap-in that is available only in a 32-bit version, but they are otherwise probably not of much interest.

Alternatively, you can open a regular Command Prompt window and type powershell or type powershell in the Windows Search box or Run dialog box.

Note – If you run PowerShell inside a regular Command Prompt window, you won’t get the default white-on-blue color scheme that you get when you open PowerShell from the menu, but it’s the same program. You can return to the regular cmd.exe command prompt by typing exit.

Windows PowerShell is subject to the same security issues as the regular Command Prompt. To modify system files or perform other administrative actions on Windows 7 and Vista, you must run PowerShell with elevated privileges. On Windows XP, to perform privileged tasks, you must be logged on as a Computer Administrator or run PowerShell under an Administrator account using runas.

I discuss this in more detail toward the end of this article in the section “PowerShell Security.”

Whichever method you use to start PowerShell, the next prompt you see should have the letters PS at the left, as shown in Figure 1 below. Type dir and press Enter, just to prove to yourself that this is not the old Command Prompt. The format of the directory listing is very different.

The PS to the left of the prompt tells you you’re using Windows PowerShell.

The PowerShell Command Prompt

Windows PowerShell prompts for commands just as the old Command Prompt environment does. It prompts, you type a command, you press Enter, it displays some sort of results, and you repeat the process over and over.

One thing that’s really improved with PowerShell, though, is that the command language is really a full-fledged programming language and creating, working with, and displaying variables is easy. For example, you might recall that you could use the set name=xxx command in batch files to store data in named variables and use the %name% syntax to retrieve the data.

In Windows PowerShell, you define variables by putting a dollar sign ($) in front of the variable’s name to both define and retrieve its value. For example, you can type the commands

$a = 40 + 7 $a

and Windows PowerShell obediently displays the computed value of a, which is 47.

Every PowerShell command is just an expression with a value, so it’s perfectly legal to type 40+7 as a command line. PowerShell prints the result. These are trivial examples, but it can be quite powerful when you’re working with objects—just type the name of an object and its property to display the value of the property, for example:

$f.path

to print the Path property of an object you’ve put into variable $f.

Remember that whatever you can put into a script, you can also type directly at the PowerShell command prompt.

Command-Line Editing

PowerShell lets you use the backspace, arrow, and other editing keys on your keyboard to modify command lines as you’re typing them and to recall, modify, and reuse previously typed commands. This will be very familiar if you’ve worked with the Command Prompt because the editing keys are identical. (There’s a reason for this: PowerShell is a standard console application just like cmd.exe.)

The arrow key functions are the most important to remember:

  • The left and right arrow keys (← and →) let you move within a command line that you’re typing, so you can go back and change a mistake at the beginning of the line without erasing and retyping the whole thing.
  • Ctrl+← and Ctrl+→ move back and forth a whole word at a time. This can save a lot of keystrokes.
  • The Home and End keys move instantly to the beginning or end of the line.
  • Normally, if you move backward in the edited line and start typing, what you type is inserted ahead of what’s already there. This is usually very handy. If you need to replace a lot of text, though, instead of erasing what’s there and then typing in the new, press the Ins key once and your typing replaces what’s already there—just type over it. The cursor changes to a solid block to remind you that this is what will happen when you type. You can press Ins again to return to Insert mode. PowerShell automatically switches back to Insert mode when you press Enter, so you can edit the next command normally.
  • The up and down arrow keys (↑ and ↓) let you step back to commands you typed previously. You can use ↑ to locate a previous command and press Enter to reissue it, or you can locate it and then edit it before pressing Enter.

There are some other function keys that you might want to know about. These shortcuts actually work in any Powershell or Command Prompt window, and with any console application:

Key

Does the following…

F2

F2 followed by a single character copies text from the previously entered command line into the current command line, up to but not including the first occurrence of the character you type. For example, if the previous command was

get-childitem c:temp | get-member

then pressing F2 | copies get-childitem c:temp into the current input line.

F3

Types in whatever was in the previous command line from the cursor position to the end of the line. For example, if you mistype a single character in a command line:

fet-childitem c:temp

and don’t realize it until you’ve pressed Enter, just type g and then press F3 to recall the rest of the line. You’ll end up with

get-children c:temp.

F4

F4 followed by a single character deletes text from the cursor up to but not including the first occurrence of that character.

F7

Pops up a list of recently typed commands. You can scroll through it using the arrow keys and press Enter to reissue the command.

F9

Lets you type in the number of a previous command. The numbers are the ones shown in the F7 pop-up. (This one would have been useful if the numbers ran backward, so that 3 meant the third command back, but they don’t, so it’s not.)

To be honest, you can work through an entire IT career without ever using these F-key shortcuts and not suffer for it, but if you can manage to remember them, they could come in handy some day. I keep meaning to remember F7, but I never do.

Copying and Pasting

Copying and pasting in the PowerShell environment works exactly as it does in any Command Prompt or console program window, again, because PowerShell is a normal console program, just like cmd.exe.

You can’t cut text out of the window; you can only copy text from a rectangular region to the clipboard. To copy from the PowerShell screen with the mouse, click the upper-left corner of the PowerShell window and select Edit, Mark. Point to the upper-left corner of the text you want to copy, press the mouse button, and drag to the lower-right corner of the text you want. Then, right-click the screen, or press Enter, to copy the text.

Note – If all the text you want isn’t visible, remember that you can scroll the window up and down during the process.

There are also keyboard shortcuts for these steps. Press Alt+Space E K to begin. You can then use the arrow keys to move the cursor to the upper-left corner of the desired text; then, hold down Shift and while holding it, use the arrow keys to move to the lower corner. Press Enter to complete the operation.

Personally, I find it easiest to type Alt+Space E K to start, switch to the mouse to mark the rectangle, and then go back to the keyboard to press Enter.

To paste text from the clipboard into the PowerShell window, click the upper-left corner of the window and select Edit, Paste. You might find it quicker to use to the keyboard shortcut: Alt+Space E P.

Pausing Output and Stopping a Runaway Program

As in the regular Command Prompt environment, you can type Ctrl+C to cancel a running PowerShell program or script.

In addition, Ctrl+S stops a printout that’s scrolling by so fast you can’t read it, and another Ctrl+S starts things up again. You can also use the scrollbar to look back through the contents of the PowerShell window.

Still, if a command is going to generate a lot of output, just as in the Command Prompt environment, it’s best to either pipe the output through the more command, which pauses after every screenful, or direct the output into a file, and then view the file with Notepad or a word processor.

Command-Line Syntax

PowerShell’s command-line syntax is at once familiar and a bit strange. I discuss this in the following sections.

Command Types

As I mentioned previously, PowerShell has built-in language statements, and it can run internal cmdlets, external commands, and scripts that contain multiple PowerShell commands.

With the exception of the PowerShell language keywords like if and foreach, which can have complex structures, commands are evaluated one line at a time, just as in the Command Prompt world.

The first word on the line is the name of the command you want to run. Any remaining text on the line is passed to the command as its arguments. Normally, spaces delimit the command name and the arguments, but you can use the single or double quotation mark () character to embed a space in an argument, as in the following command:

command /abc “argument with spaces”

In an unusual twist, to type a program name that has spaces in its name or path, you must use single or double quotes around the name and must precede the command with an ampersand, as in this example:

&"command with spaces" /abc argument

PowerShell finds the program that corresponds to the command name by searching the following places in this order:

  1. PowerShell first looks through its alias list, which is a list of shorthand names for commands. PowerShell is installed with nearly 150 built-in aliases predefined. For example, cd is set up as the alias for the Set-Location cmdlet. As you work with PowerShell, you’ll find that you’ll soon want to define your own custom aliases for the commands you use most often.
  2. If an alias name is matched, PowerShell replaces the command name in your command line with the alias definition and the search process over.
  3. PowerShell then scans the names of functions that have been defined by the current script, if you’re running a PowerShell script, or that have been defined at the command line. If a function with the specified name is found, the function is called and passed the command-line arguments. You can define your functions in the PowerShell language in scripts or at the command prompt. They work and act just like cmdlets.
  4. If the command name is not found in the alias list, PowerShell searches the list of cmdlets that come preinstalled with Windows PowerShell or have been added by a snap-in that came with an added application or service. If it’s found, the cmdlet is run.
  5. If the name doesn’t match a cmdlet, PowerShell uses the standard search path mechanism to look for an external program, much as cmd.exe does. It looks first in the current directory and then through the directories listed in the PATH environment variable for a file with the stated command name and whose extension is a recognized program extension. In each folder searched, PowerShell does the following:
    • It first looks for the extension .ps1, which is used for PowerShell scripts in PowerShell versions 1.0 and 2.0. If a script file is found, PowerShell runs the script (subject to the security restrictions that I discuss shortly).
    • If a .ps1 file is not found, it scans through the extensions listed in the PATHEXT environment variable, just as cmd.exe would. This mechanism lets it find and run standard Windows executable files (.exe files), both GUI and console applications. PATHEXT also includes .cmd and .bat, so that PowerShell can run normal Command Prompt batch files—it fires up a copy of cmd.exe to do so. Likewise, for .vbs, .js, .vbe, and .jse files, it fires up WSH to run these scripts, and for .MSC files, it runs the snap-in through the Microsoft Management Console.
  6. Thus, you can run PowerShell cmdlets and scripts, console applications, Windows programs, batch files, or any other sort of program from the PowerShell environment. notepad still starts Notepad.

There are exceptions to the normal search processing, though:

  • If your command includes an explicit path as part of the command name, PowerShell runs the specified file. For example, the command c:binsort.exe would run that specific copy of sort.exe and would not try to search for sort as an alias or in the PATH locations.
  • To improve security, PowerShell will not run a .ps1 PowerShell script that it found in the current directory before it searched the PATH list. It will tell you about it, but it won’t run it. It will run only PowerShell scripts that it finds in the PATH or those to which you’ve explicitly typed a path.
  • You can run a file in the current directory by preceding its name with ., as in .myscript.ps1. This is an explicit path, so it satisfies PowerShell’s security requirement.
  • Even then, PowerShell might not run scripts at all, depending on additional security settings that I discuss in the next section.
  • It’s conceivable that more than one PowerShell snap-in might define a cmdlet with the same name. PowerShell searches through snap-ins from the most recently installed back toward the first installed, and the first snap-in found that defines the cmdlet name is the one that’s used. Also, you can import (load) new snap-in cmdlet modules while PowerShell is running, and the same ordering applies: Snap-ins are examined from the most recently imported toward the oldest.
  • Or, you might have defined an alias that has the same name as an existing cmdlet. If you type the aliased name, you’ll get the command that the alias specifies, not the original cmdlet.
  • To run a specific cmdlet from a specific snap-in without hitting this ordering or aliasing problem, you can precede the cmdlet name with the name of the snap-in module, followed by a backslash. For example, Microsoft.PowerShell.Utility Get-Date runs the Get-Date cmdlet in the Microsoft.PowerShell.Utility module even if you’ve defined an alias for Get-Date or another module has defined a cmdlet with the same name.
  • For more information on command searching, type help about_command_ precedence at the PowerShell command prompt.

I know this can seem tedious in an introduction, but you need to know the details of the search system to get your own scripts to run and to diagnose problems if someday the program that runs isn’t the one you expected.

The main thing you should take from this is that if you want to develop and use your own PowerShell scripts, you will want to create a specific folder to hold them and put that folder name into the Windows PATH environment variable. If you’ve already set up such a folder for batch files or WSH scripts, you can use the same folder for PowerShell scripts.

Redirection and Pipes

You can redirect the output of commands you run from the PowerShell prompt and in PowerShell scripts into files. The usual operators—|, >, <, >>, and so on—work as they do in the Command Prompt environment.

In PowerShell, though, remember that most cmdlets emit objects, not text. The output of these cmdlets turns into text listings only when they land in the PowerShell window, are redirected to files, or piped to standard Windows console commands. You can control the formatting of these text listings using specific cmdlets.

Cmdlets and Objects and Scripts, Oh My!

The PowerShell world introduces new, somewhat confusing concepts and terminology, and I suspect that your first reaction will be similar to mine: I looked at a few PowerShell scripts; scratched my head; and thought, “I wonder if there are any donuts left in the kitchen?” At first, it all seemed pretty opaque and possibly not worth investigating. Fortunately, this feeling didn’t last long. (Neither did the donuts.)

The biggest obstacles are the strange names of the cmdlets and the unusual command-line syntax. Cmdlets have names like Remove-ItemProperty, Get-Content, Wait-Job, New-Alias, and so on. This can help make sense of it:

  • Cmdlet names are case insensitive. You can type wait-job just as well as Wait-Job. The capitalization is used to make the words more distinct when you read the documentation.
  • Microsoft’s programmers chose to use a noun-verb convention for naming the cmdlets to make the names more clearly say what the cmdlets actually do. The dash is just part of the name. Rename-Item isn’t some sort of combination of a Rename command and an Item command. The name is all one word: Rename-Item, and you can guess from this name that it probably renames whatever items it’s given.

    Yes, the names tend to be long and cumbersome to type. A Unix programmer would have chosen a name like ri for that Rename-Item command. But, ri doesn’t really tell what it does. As it turns out, PowerShell does have a built-in alias for Rename-Item, and the alias is…ri. As you learn PowerShell’s commands, you might start by using the long names to help remember what the commands do and then scan through the alias list and start learning their shorter abbreviations.

  • The names of cmdlet command-line options are similarly long. For example, the get-process cmdlet can take the following optional arguments:

-Name “string”
-ComputerName “string”
-FileVersionInfo
-Module
-Id integer
-InputObject object

Again with the long names! Who can type -InputObject quickly without making three typos along the way? Well, it turns out that you don’t have to type the entire option name, just enough to distinguish the desired option from any others that start with the same letters. So, you can type ­-input or even -in instead of -InputObject. You just can’t shorten it to just -i because that’s not enough to distinguish between -Id and -Inputobject.

Some command can be shortened even more. For example, a typical new-alias command looks like this:

new-alias -name shortname -val realcommandname -descr “Brief description”

But, you even can omit the parameter switches, in this really short version of the command:

new-alias shortname realcommandname

The two arguments in this case are called positional parameters because PowerShell has to figure out what they are based on their position in the command line. You can see which parameters can be specified this way by looking at a cmdlet’s syntax description. If you type new-alias -?, you can see that the syntax is

New-Alias [-Name] [-Value] [-Description ] [-Force] [-Option {None | ReadOnly | Constant | Private | AllScope}] [-PassThru] [-Scope ] [-Confirm] [-WhatIf] []

Notice that the -Name option indicator itself is listed in [ ] brackets, so it’s optional, but the value after it isn’t. This argument must always be there, so it can be interpreted by its position. The -Value string is listed the same way, but none of the other arguments are.

The other main obstacle to learning to use PowerShell is the strange syntax with commands like the example I gave earlier

dir | where-object {$_.LastWriteTime -lt (get-date).addmonths(-6)} | remove-item

The dir and remove-item parts are self-explanatory, but the middle part is, well, non-obvious. This where you hit the PowerShell learning curve, and the only thing to do is expose yourself to a lot of it. It will start to make sense pretty quickly. My advice is to read as many PowerShell scripts as you can. Read them like literature, get a feel for the language, and work out what they do. I’ll just point out a couple of things about that example command here.

The where-object cmdlet is a filter. It reads a stream of objects from the previous command in the pipeline, evaluates a true/false value for each one, and passes along only the objects for which the value is true. In the example, the true/false value is provided by the part within curly brackets:

{$_.LastWriteTime -lt (get-date).addmonths(-6)}

Caution – It’s important to know that this expression isn’t handled directly by where-object. If it was, then conceivably every cmdlet might have a different way of constructing these expressions, which make would things inconsistent and difficult to master.

Instead, this expression format is part of the PowerShell language itself. Technically, where­-object expects the body (code) of a function on its command line. The curly brackets signify that you’re typing the body of a function that you’re defining on-the-fly without giving it a name, and that function is given to where-object to use to evaluate each of the file objects it scans. (This little function is technically called a lambda, but that’s not too important here.)

Let’s pick it apart. There are three parts:

$_.LastWriteTime

$_ is a placeholder for the object that where-object is examining. $_.LastWriteTime picks up the LastWriteTime property from that object. For a file or folder object, it’s the date and time that the file was last modified.

-lt

This does a comparison of two values, and it’s true if the first value is less than the first. In other words, the expression {a -lt b}, is true if value a is less than value b. In this instance, the test is true if the file’s LastWriteTime is less than (earlier than) the time that comes after -lt.

(get-date).addmonths(-6)

This is the oddest part, but watch how it works: The get-date cmdlet is run. With no arguments, it spits out a .NET System.DateTime object representing the current date and time. In this simplest form, it’s like Now() in VBScript. The parentheses around it indicate that we are going to treat the result of the cmdlet as a value. addmonths is one of the standard methods of the System.DateTime object. In this case, we end up with the current date with six months subtracted from it—in other words, the date six months back.

The end result is that this expression is true if the file was last written more than six months ago. The curly brackets turn this expression into a function so that where-object can evaluate it for each of the objects it examines.

The output of this where-object command is just those file objects that were last modified more than six months ago. The rest of the command line feeds that stream of objects to remove-item, which deletes the files they represent. The end result is that this command purges a directory of old, abandoned files.

Now, I didn’t just write that command off the top of my head. I had to learn the basics of cmdlets first, so I knew to write:

dir | where-object {some expression} | remove-item

Then, I had to learn about the properties of the file and folder objects to know to use LastWriteItem and the System.DateTime object to find the addmonths property. To help with that job, interestingly enough, there are cmdlets that describe the properties of any object they encounter. I describe that next.

Getting Help

The most important PowerShell command to learn first is the one that helps you learn about the others! It’s called get-help, but it has a predefined alias named help, so you can use either of these command names interchangeably. PowerShell has a lot of built-in help—477 different topics, in fact, at the time I wrote this.

Here are some tips:

  • Type the word help by itself to get a quick introduction to the online help system.
  • After help or get-help, you can type a word, cmdlet name, or partial cmdlet name. You can also type a phrase enclosed in quotation marks. If more than one topic, cmdlet name, or description matches what you typed, get-help prints a list of all matching help entries. You can then type help followed by the specific entry name that interests you to get the details. If exactly one name or description contains the word or phrase you typed, get-help prints the help information for that topic.
  • Some cmdlets have additional help information available. For example, you can see some examples of using the new-alias cmdlet by typing help new-alias -examples. Common options for additional information are -examples, ­-detailed, and -full. The main help page for a topic tells you whether these expanded pages are available.
  • The help text appears in the console window and by default is piped through more so it stops after every screenful. Press Enter to go on to the next page.
  • Alternatively, you might find it easier to direct help output into a file by adding, for example, >x to the end of the help command line; then, type notepad x to read the text.
  • There are help entries covering every one of the installed cmdlets and additional articles on different topics. These articles start with about_. For example, help about_execution_policies prints information about the scripting security restriction system. (You can also type help about_exec and get the same result because only one entry contains the string “about_exec” in its title or description.) To see a list of all of these “about” entries, type help about.

This online help system is great for locating cmdlets based on words in the description of the job they do and for learning about their command-line syntax after you’ve found a cmdlet that interests you.

Tip – In the online syntax descriptions, the following conventions are used:

[ ] square brackets indicate optional command arguments.

{ } curly braces usually indicate a series of options from which you can choose, with a vertical bar | between the options.

< > angle brackets surround a value that you have to supply yourself. For example, [-Description ] indicates an optional argument. You can omit it, or you could type something like -description “some text”. As I mentioned in the previous section, you could probably abbreviate this to -descr “some text”.

Prompting to Complete Commands

If you type a PowerShell command that requires specific arguments, but omit some or all of the required arguments, PowerShell prompts for them by name. Here’s an example: If you type set-alias without any arguments, PowerShell prompts for the required -name and -value arguments. Here’s how it looks:

PS C:Usersbknittel> set-alias
cmdlet Set-Alias at command pipeline position 1
Supply values for the following parameters:
Name: ax
Value: get-alias

(I typed the responses in italics.) This mechanism can help you as you learn to use the cmdlets, but remember that PowerShell won’t prompt for optional arguments, just the required ones.

Personally, I don’t find this mechanism that useful and never trigger it deliberately. You should know it exists though because if you omit a required argument from a command, PowerShell might prompt you in this way and you might find it confusing at first.

Aliases

As I mentioned previously in “Command-Line Syntax,” when you type a command, PowerShell looks through list of aliases, functions, cmdlets, and external programs to find the program you want to run.

Because people who do a lot of work at the command prompt are so used to typing commands like cd and dir, PowerShell comes with predefined aliases for many of these familiar commands. Because the names of many of the cmdlets are tediously long, there are predefined aliases for many of the cmdlets that are only two or three characters long. (This should make Unix users happy!) The idea is that you’ll find that there are just a few commands you tend to use over and over. After you know which these are, you can look up their short aliases and use those to save time typing.

One serious limitation of aliases, though, is that they can map only one command name to another. An alias definition can’t include command-line arguments. I would really like to define an alias named h that issued the command cd $home, which changes back to your user profile “home” directory, but this isn’t supported. It’s really unfortunate.

How to Get a Listing of Aliases

You can see a list of all the built-in aliases by typing alias (which, as you’ll see, is an alias itself, for the real command name get-alias). I find it easiest to view this list in a text file by typing two commands:

alias >x
notepad x

You’ll notice the alias named %, for ForEach-Object, and the alias named ?, for Where-Object. The latter, used in that “delete old files” command example I gave earlier in the chapter, would look like this:

dir | ? {$_.LastWriteTime -lt (get-date).addmonths(-6)} | remove-item

Personally, I don’t think it this reads well, but if I got used to typing it, it might save some time. It’s up to you whether you want to use shortcuts like this, so nobody’s forcing anything on you. The idea is to use the shortcuts that make sense to you and ignore the others.

How to Define a New Alias

You can define a new alias by typing a command like this:

new-alias -name shortname -value
realcommandname -description “Brief description”

but substituting the name of the alias you want to create for shortname and the command that the alias should run for realcommandname. If the alias already exists, you have to add -force to the command to replace the old one. I show you how you can shorten this command later in this article.

You should know that alias definitions don’t survive when you close your PowerShell window. The next time you run PowerShell, your custom alias will be gone. If you come up with favorite aliases you want to keep, see the section on Profiles at the end of this article.

Navigating Directories and Other Locations

In the command-line world, you use typed commands to navigate up and down through folders and disk drives. Windows PowerShell uses the same cd command as the Command Prompt to change directories, so familiar commands like

cd Users
cd ..
cd subfolder

still work. You can use the Tab key to automatically fill in partially typed file and folder names, just as in the Command Prompt environment.

You can also take advantage of directory names stored in PowerShell variables. Your user profile folder path is stored in variable $home, so you can use the command cd $home to return to your profile directory from any location.

Now, here’s something really interesting: You’re used to using cd to move around the file system. In PowerShell, you can also navigate through the Registry!

Here’s how it works: Just as Windows recognizes different drive letters, like this:

c:usersbknittel
d:saved_picturesFebruary2010Yosemite
e:setup.exe

PowerShell recognizes additional drives, which it calls providers, that treat the Registry and the lists of environment variables, aliases, PowerShell variables, defined functions, digital certificates, and Web Services for Management just like disk drives. You can specify paths to these elements, list them with dir, and in some cases even use cd to navigate through them.

The default provider drives on Windows 7 are listed in Table 1.

Table 1  Provider Drives on Windows 7

Drive Name

Contains

A:, B:, C:, and so on

Disk drives (FileSystem provider)

Alias:

List of PowerShell aliases

Cert:

Digital certificates

Env:

Environment variables

Function:

Defined functions

HKCU:

Registry section HKEY_CURRENT_USER

HKLM:

Registry section HKEY_LOCAL_MACHINE

Variable:

PowerShell variables

WSMan:

Windows Services Management connections to the local and remote computers

Name completion works with these drives, too. For example, if you type dir hklm:soft and press the Tab key, PowerShell changes soft to SOFTWARE, which is the first Registry key that matches the partial name you typed. You can continue the path by typing and another part of a key name.

Try typing these commands at the PowerShell prompt (and notice that you don’t have to capitalize them; the names are case insensitive):

dir hklm:software

This lists the keys under HKEY_LOCAL_MACHINESOFTWARE.

cd hklm:software

Makes the Registry your “current location.”

dir

Lists the keys in this current location.

cd $home

Returns to the file system in your profile folder.

dir cert:currentuser

Lists certificates associated with your use account.

dir variable:

Lists all variables currently defined in Windows PowerShell.

dir env:

This lists all defined environment variables.

Many PowerShell cmdlets can work with objects specified by their paths whether the paths point to a file, a Registry key, a certificate, or whatever. For example, the del command (which is an alias for delete-item) can delete a Registry key just as easily as a file, with a command like del hkcu:softwarebadkey.

PowerShell Security

Because Windows PowerShell can be used to change Windows settings and has the potential, if run by a privileged user, of undermining Windows’ security system, Microsoft has taken care to be sure that it’s difficult to run PowerShell scripts without your taking intentional steps to enable them. There are additional barriers to running scripts that come from the Internet, via email, Instant Messaging programs, and so on. This was done to avert the possibility that hackers might figure out ways to exploit potential flaws in, say Internet Explorer, to install and run PowerShell scripts on your system without your permission.

PowerShell Scripts and User Account Control

Windows PowerShell was designed first and foremost for managing Windows, so you will end up wanting it to do things that require Administrator privileges. On Windows 7 and Vista, PowerShell, requires elevated privileges—just running it from a Computer Administrator account isn’t enough. Either open an elevated command prompt and then type powershell or use any of the methods you’d use to run cmd.exe with elevated privileges, but run powershell.exe instead.

On Windows XP, to perform administrative functions, you’ll have to be logged in as a Computer Administrator when you start PowerShell. Alternatively, you can use the runas command to start powershell.exe in the context of an Administrator’s user account.

Whatever version of Windows you’re using, you’ll probably want to try this right away, as you want to use a privileged PowerShell command to let you run PowerShell script files. I describe this command next.

Script Execution Policy

As initially installed, PowerShell is set up so that it can be used interactively at the command prompt but will not run scripts. This does make sense. The majority of Windows users will never touch PowerShell, and nobody knows what future bug might be discovered that would let hackers silently send them malicious PowerShell scripts via Internet Explorer, Adobe Acrobat, YouTube, or who knows what. Better to be safe than sorry.

Power users just have to change the default script execution policy from Restricted to, as I recommend, RemoteSigned. Table 2 lists the possible policy settings.

Table 2  PowerShell Script Execution Policy Settings

Setting

Description

Restricted

This is the default setting. No PowerShell scripts will run at all, under any circumstances.

AllSigned

Only digitally signed scripts (including profile scripts, which I describe in the next section) will run; in addition, you are prompted to grant permission to run scripts signed by the specific certificate used.

RemoteSigned

Scripts (and profiles) that have been written locally will run.

Scripts that have been downloaded from the Internet will not run unless they are signed and you have approved the signing certificate.

Unrestricted

All scripts will run, but you are warned about scripts that have been downloaded and must approve them before they’ll run.

Bypass

Any script will run, regardless of its origin. This is a potentially very risky setting and should be used only in very specific circumstances, where some other security system is in place to prevent rogue scripts from running without your permission.

(Undefined)

If no policy setting is in place, PowerShell treats the setting as Restricted and no script will run.

I recommend the RemoteSigned setting. Scripts you write and store on your computer or retrieve across your local area network will run without any problem, but scripts that arrive via programs with Internet connectivity won’t run unless they have a digital signature and you’ve confirmed that you trust the person or company that signed the script. This is a good security compromise.

To change the setting, open a privileged PowerShell window as described in the previous section. Then, type the command

set-executionpolicy remotesigned

You will have to confirm that you want to make this change by typing y and Enter. (You can disable that prompt by adding -force to the command line.)

Now, you can run PowerShell scripts and profiles. .

There are few things you should know about this security setting:

  • If your computer is part of a corporate domain network, this setting is probably under the control of your network manager via Group Policy. Type get-executionpolicy to see what your current setting is. You might not able to change it yourself.
  • If you are forced into, or choose, the AllSigned policy setting, you’ll have to digitally sign any script you want to run. It’s a cumbersome process, but it’s not too bad after you get used to it.
  • You might recall that files downloaded from the Internet are marked as “potentially risky” through information stored in a separate data stream associated with the downloaded file. To remove this marker from a downloaded script that you are certain is safe, use Windows Explorer to open the file’s properties dialog box and click Unblock. It will now be considered a local file and will run under the RemoteSigned execution policy.

Finally, remember that if you have a local area network (LAN) but not a Windows domain network, and the scripting execution policy isn’t set by Group Policy, you’ll have to change this setting on every computer on your network that you want to manage using PowerShell.

PowerShell Profiles

As I showed in the previous sections, you can customize the PowerShell environment to suit your preferences by adding custom aliases, adding directories to the path, and so on. It would be a pain to have to retype these commands every time you started PowerShell—and you don’t have to if you set up a PowerShell profile, which is a script of commands that PowerShell runs every time you start a new instance. You might want to put commands of this sort in a profile script:

new-alias -name “n” -val
“notepad” -descr “Edit a file with Notepad”
$env:path += “c:PSscripts”

so that your favorite, custom aliases will be available every time you use PowerShell.

Here’s the skinny: Whenever you start Windows PowerShell in any of its various flavors (the regular command-line PowerShell, the GUI PowerShell ISE, or a PowerShell variant that’s embedded inside another application), it looks for profile scripts in the following two locations, in this order:

%windir%system32WindowsPowerShellv1.0

where %windir% is the folder in which Windows is installed, usually c:windows, and

%userprofile%[My] DocumentsWindowsPowerShell

where %userprofile% is your account’s profile folder, usually c:Usersusername on Windows 7 and Vista and c:Documents and Settingsusername on Windows XP.

Within these two folders, the different flavors of Windows PowerShell look for different profile filenames. Every PowerShell variant looks first for a script named profile.ps1 and runs it if it’s found. The command-line PowerShell then looks for a profile script named Microsoft.Powershell_profile.ps1 and executes that one if it’s found. The GUI PowerShell ISE program, on the other hand, looks first for profile.ps1 and then Microsoft.PowerShellISE_profile.ps1.

Profile scripts in the %windir% folder affect all users on the computer, while profile scripts in your %userprofile% location affect only shells that you use. So, you can decide to make some customizations available to everyone and make some just for yourself by setting up separate profile scripts. Likewise, you adjust every PowerShell variant by putting commands in profile.ps1, or you can season the different PowerShells to taste by putting commands in the version-specific files.

PowerShell executes each of the scripts it finds, so the environment you end up with is the result of the cumulative changes made by all the script(s) that you’ve set up.

Creating a PowerShell Profile – PowerShell has a predefined variable named $profile that points to the version-specific profile file in your %userprofile% folder. For example, in my command-line PowerShell, $profile has the value “c:UsersbknittelDocumentsWindowsPowerShellMicrosoft.PowerShell_profile.ps1”.

So, you can instantly create a PowerShell profile by typing the command notepad $profile. Notepad will ask whether you want to create a new file. Click Yes, and you’re ready to go.

To create a profile for all users in folder %windir%system32WindowsPowerShellv1.0 on Windows 7 or Vista, remember that you’ll need to use an elevated Command Prompt or PowerShell instance. This folder name is stored in variable $PSHOME, so from PowerShell you can use the command notepad $pshomeprofile.ps1 or notepad $pshomeMicrosoft.PowerShell_profile.ps1 to create or edit the file.

However, and this is a big however, profile scripts are still scripts and PowerShell will only run profile scripts that meet the security guidelines I described in the previous section. Remember that the default execution policy is Restricted, so profile scripts won’t run at all (unless you’re on a Windows domain network and your network manager has enabled script execution).

To take advantage of the profile feature to customize your PowerShell environment, you will need to change the execution policy and possibly digitally sign your scripts. The previous section tells you how to do this.

This article is excerpted from the book Windows 7 and Vista Guide to Scripting, Automation, and Command Line Tools, copyright Pearson Education, all rights reserved. Reprinted with permission.

Published: October 22, 2018

Updated: March 17, 2023

In this short PowerShell introduction, I’ll explain what PowerShell is and what it was created for, as well as provide a list of useful resources that can help you learning PowerShell scripting and make your working life easier.

Windows PowerShell is a Windows command-line shell created to simplify administration of various Microsoft products. For example, the PowerShell ISE adds syntax coloring, tab completion, visual debugging and more. It is basically a programming language that is built on the .NET framework; you can use this scripting language to enter single PowerShell commands or write longer PowerShell scripts. The Windows PowerShell environment consists of two applications: the PowerShell Console and PowerShell ISE (which stands for “integrated scripting environment”). The latter gives you better possibilities to write, run and test scripts.

PowerShell commands are called cmdlets. You can enter a single cmdlet at the command line or combine multiple cmdlets to create scripts that perform complex administrative tasks. Windows PowerShell includes more than hundred cmdlets for performing many basic day-to-day administrative tasks. You can interact with various objects, including users, groups, Group Policy and files.

PowerShell provides you with the power to easily get data about current system settings, make changes to objects, manage services, and manage access to systems, including file systems. Having a solid knowledge of PowerShell scripting will enable you to reduce the time you have to spend on many administrative functions, without having to purchase and implement third-party tools.

Start learning PowerShell scripting with our PowerShell scripting tutorial for beginners. This tutorial covers the basics, such as launching the PowerShell on your desktop and preparing to run PowerShell scripts, and also provides detailed information about PowerShell cmdlets.

Here are other resources that will be helpful in getting started with PowerShell and PowerShell scripting:

  • Active Directory administration:
    • How to Create New Active Directory Users
    • Create AD Users in Bulk and Email Their Credentials
    • How to Lock, Unlock, Enable and Disable AD accounts
    • How to Create, Change and Test Passwords Using PowerShell
    • How to Create, Delete, Rename, Disable and Join Computers in AD
    • How to Add and Remove AD Groups and Objects in Groups
    • Managing OUs and Moving Their Objects
    • How to Monitor User Logons in a Domain
    • How to Export Members of a Particular AD Group
    • How to Export a Computer List from Active Directory
    • How to Check If AD User Account Is Disabled
    • How to Find Inactive Users in Active Directory
  • Windows Server administration:
    • How to Get, Edit, Create and Delete Registry Keys
    • How to Add, Delete and Change Local Users and Groups
    • How to List All User Accounts on a Windows System
    • How to Get Server Inventory across Your Network
    • How to Detect Modifications to Startup Items in the Windows Registry
  • File Server administration:
    • How to Manage File System ACLs
    • How to Manage Files and Folders
    • Ransomware Protection Using FSRM and PowerShell
    • How to Get an NTFS Permissions Report
    • How to Determine Who Deleted a File from Your Windows File Servers
    • How to Determine Who Changed a File or Folder Owner
  • Office 365 administration:
    • Ten Most Useful Office 365 PowerShell Commands
    • How to Create, Assign Licenses to, Disable and Delete Office 365 Accounts
    • How to Configure User Passwords to Never Expire
    • How to Detect Who Was Accessing A Shared Mailbox in Office 365
    • How to Detect Who Modified Mailbox Permissions in Exchange Online
    • How to Stay on Top of Permissions Changes to Public Folders in Exchange Online
  • Miscellaneous:
    • How to Automate PowerShell Scripts with Task Scheduler
    • Windows PowerShell vs Command Prompt (cmd): Which to Choose
    • Most Useful SharePoint PowerShell Commands
    • Using PowerShell to Create ZIP Archives and Unzip Files
    • PowerShell Variables and Arrays

Jeff is a former Director of Global Solutions Engineering at Netwrix. He is a long-time Netwrix blogger, speaker, and presenter. In the Netwrix blog, Jeff shares lifehacks, tips and tricks that can dramatically improve your system administration experience.

More great reading

Windows PowerShell Introduction

My goal on this page is to persuade Windows administrators that Microsoft’s PowerShell is a friendly scripting language, which is well worth learning.

Using my examples and learning points, you will soon be able to interrogate the server’s operating system.  So get started, by downloading and installing Windows PowerShell, together with .Net Framework.

 Windows PowerShell Introduction Topics

  • Who is PowerShell designed for?
  • Your first seven steps to learning PowerShell
  • My Challenge – Start your PowerShell journey
  • What’s Cmdlets in PowerShell v 3.0

 ♣

Who is Windows PowerShell Designed For?

What impresses me about PowerShell is that even as an amateur, you can get started easily and you will soon be creating interesting scripts. The hidden message is that PowerShell works at many levels, moreover, you can quickly rise through these levels. As your journey proceeds, PowerShell teaches you about scripting theory, and scripting theory teaches you which constructions to look for in PowerShell.

The vision behind PowerShell is to provide cmdlets (scripts) which automate repetitive tasks.  There is a feeling, at least in Exchange 2003/7, that people cannot find settings because they are hidden underneath so many levels of sub-menus.  What I find is that it soon becomes as fast to issue a few commands in the Microsoft Shell, as to configure the same settings through a GUI.

Admins who have always wanted a command line shell for interactive scripting are going to enjoy PowerShell.  The most amazing feature of PowerShell is that it lets you think in previous language, while you figure out its native ways of operating. Using the built-in Aliases, or creating new Aliases is the key to this transition.

Your First Seven Steps to Learning PowerShell

  1. Download PowerShell (Get an OS specific version)
  2. Begin with familiar old dos commands: dir, CD or Ipconfig (Just to get comfortable)
  3. Make a collection of Verb-Noun pairs, e.g. set-Executionpolicy and Get-Childitem
  4. Call for help with Get-Help wmiobject and master Get-Member
  5. Create lots of scripts or Cmdlets
  6. Deploy the Pipe symbol | (Join commands | filter)
  7. Master $_.  This construction means the current object in the pipeline.
    For example: where | {$_.name -Contains «Microsoft»}

Getting Started With PowerShell

No other scripting language is so easy for the newcomer, yet offers so much sophistication for the experienced script writer.  One reason that I want to introduce you to PowerShell is you can still use all your old commands such as: cd, dir, and even Ipconfig.  My vision is that little by little, you can progress from commands you already know, e.g. dir, to PowerShell’s Get-ChildItem.

Now I don’t pretend that it’s easy to become an expert at PowerShell, I merely want to make the point that it’s easy to begin that scripting journey.  Just as in golf, most people can get the ball airborne with a sand wedge, but only a professional can hit a ball out of the rough, clear a water hazard, then hold the ball on a down-slope.  PowerShell is like golf in that anyone can play, but few will have the effortless control of a professional.  To stretch my analogy to the limit, just as we can play along with our favourite golfers from the comfort of our armchairs, so we can emulate PowerShell’s experts by copying and pasting their code.

To get you started, here are five examples to type at the PS prompt type:

  1. Get-Command
  2. Get-Command get*
  3. Get-Eventlog system
  4. Get-Eventlog system -newest 100
  5. Get-Eventlog system -newest 100 | where {$_.eventid -eq 20}

See more on getting started with PowerShell commands

Guy Recommends: Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.

Download your free copy of WMI Monitor

My Challenge – Start Your PowerShell Journey

My aim in this introduction to PowerShell is to get you writing your own PowerShell cmdlets.  Meanwhile, here is my challenge to you: in ten minutes you will be able to perform all the tasks that you currently achieve at the CMD prompt.  Moreover, at the end of half an hour you will be issuing PowerShell commands that are just not possible with cmd.exe.

My assumption is that you have successfully installed PowerShell and .NET Framework 2.0, 3.0 or 4).  Begin by clicking Start, Run, and type powershell in the dialog box; alternatively, create a short cut to powershell in the Quick Launch area of the Taskbar.  See more on PowerShell’s version checker.

Try out a Few PowerShell Commands

Normally, when people move to another scripting language their old trusty commands don’t work in the new shell.  Well, you will be pleasantly surprised that when you migrate from cmd.exe, old favorites such as cd and dir are available thanks to PowerShell’s Aliases.  In a short time you will adapt to the new ways of doing old tasks; for example, set-location is the equivalent of cd, and Get-Childitem achieves the same result as dir.  In addition, PowerShell allows you to run all the native Windows executables such as Ipconfig, NetSh and NetDiag.

Thanks to this built-in library of Aliases, those coming from UNIX, perl or .NET can also make an easy transition to PowerShell.  I don’t want you to underestimate the body of knowledge required to be productive in PowerShell, I just want to emphasise that it’s easy to take that first step and build on familiar commands from your existing scripting language.

Principle 1:  At the heart of every PowerShell command is a Verb-Noun pair.  You start with verb, add a hyphen and then finish with a noun.  For example, set-location, which is the equivalent of cd (change directory) in DOS.  If you find exceptions that only require the noun, this is because PowerShell’s intelligence adds the default verb ‘get’.  For example if you type, ‘childitem’, PowerShell assumes you mean Get-Childitem.  More good news, advanced scripters can create their own aliases. 

PowerShell Introduction – Simple Examples

I realize that these are Windows rather than Exchange 2007 examples but I want to get you up and running:
Preamble, Start, Run, PowerShell.  In the shell type:

Get-Process
or
Get-Eventlog system

Principle 2:  Create lots of scripts or cmdlets.  What I mean is save your commands in a text file with a .ps1 extension, for example ProcessAll.ps1.  Moreover, save that file into PowerShell’s working directory.  Now you are ready to execute these cmdlets from within this Microsoft Shell, for example:  .\ProcessAll.  Your two key characters are the dot and the backslash.  The secret is get into the rhythm: dot, backslash then filename.  There is no need to add the .ps1 extension, also avoid spaces.

.\cmdlet_filename

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM) v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

The Knack

The knack is to store all your cmdlets in a folder which you can easily reach from the PowerShell prompt.  At the risk of teaching my grandfather to suck eggs, I suggest that you adopt one of these strategies.

a) Save all cmdlets to the default PowerShell directory.
b) Once PowerShell launches, immediately change directory to the folder containing your cmdlets
    cd C:\ cmdlets.
c) There is an advanced technique to re-program the default PowerShell directory to a folder of your choice.

If all else fails just type the complete path:
C:\Documents and Settings\GUYT\Documents\PSConfiguration\ProcessAll
(Or D:\scripts\ProcessAll)

  Auto-completion:
To save typing, and reduce the risk of making a spelling mistake, invoke auto-completion by pressing tab.

Auto-completion examples
Get-ev [tab] auto-completes to –> Get-Eventlog
set-lo [tab] auto-completes to –> set-location

Example of a PowerShell Cmdlet

# This cmdlet generates a report about memory in active processes
# Memory usage (>100000000)»
Write-Host Report generated at (Get-date)
Write-Host «»
Get-Process | where-object { $_.VirtualMemorySize -gt 100000000 }

See more on getting started with PowerShell

PowerShell’s Built-In Help

PowerShell’s help is clear, concise and full of useful examples.  Put your faith in PowerShell’s help.  Cast aside negative experiences of other help files.  Overcome your pride and ask for help.  All that you need to query the vast help information store, is either precede the item with ‘help’, for example, help Get-Member; or else append -? for example, Get-Process -? (hyphen question mark).  The executable powershell.exe even has its own help, try this at the PS prompt, type: powershell -?

Another useful sister cmdlet is: Get-Command, which lists the built-in cmdlets.  Better still, try the * wildcard:

Get-Command *service.

»

Summary of PowerShell Introduction

PowerShell is Microsoft’s new scripting language. It is designed to supersede VBScript and eventually to replace the ‘Dos box’. What makes it easy to get started is that all the old DOS commands still work at the PowerShell command line.

Trust me; it really is easy to get started with PowerShell Verb-Noun commands. Therefore make sure that you download a version for your operating system, and start learning from the PowerShell script examples that I will supply on other pages.

If you like this page then please share it with your friends


See more Microsoft PowerShell tutorials

• PowerShell Tutorials   • Introduction   • PowerShell 3 New Aliases   • -Online   • 3 Key Commands

• Top 10 PowerShell Aliases   • PowerShell Alias   • PowerShell $_ Variable   • Free CSV Import Tool

• PowerShell Parameters   • Cmdlet scripts   • Vista PowerShell   • Windows 8 PowerShell 3.0

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Настраиваемое масштабирование windows 10 как сбросить
  • Учет трафика по приложениям windows 10
  • Общий буфер обмена android windows
  • Windows server 2012 r2 server cal 2012
  • How to open trash windows