Welcome to PowerShell! This chapter will introduce you to the PowerShell console. You'll learn how to configure the console including font colors and sizes, editing and display options. This is a good idea because nearly everything in the PowerShell console is text-based.
Topics Covered:
Starting PowerShell
After you installed PowerShell, you'll find the PowerShell icon on the Start Menu in the program folder Windows PowerShell. Open this program folder and click on Windows PowerShell. The PowerShell console comes up. BTW, if you aren't able to find the program folder, PowerShell is probably not installed on your computer. It is an optional download from Microsoft for Windows XP, Server 2003 and Windows Vista.
You can also start PowerShell directly. Just press (Windows)+(R) to open the Run window and then enter powershell (Enter). If you find yourself using PowerShell often, open the program folder for Windows PowerShell and right-click on Windows PowerShell. That will give you several options:
- Add to the start menu: On the context menu, click on Pin to Start Menu so that PowerShell will be displayed directly on your start menu from now on and you won't need to open its program folder first.
- Quick Launch toolbar: Click Add to Quick Launch toolbar if you use Windows Vista and would like to see PowerShell right on the Quick Launch toolbar inside your taskbar. Windows XP lacks this command so XP users will have to add PowerShell to the Quick Launch toolbar manually. The way to do that is described in the next text box.
- Keyboard shortcuts: Administrators particularly prefer using a keyboard instead of a mouse. If you select Properties on the context menu, you can specify a key combination in the hot-key field. Just click on this field and press the key combination intended to start PowerShell, for example (Alt)+(P). In the properties window, you also have the option of setting the default window size to start PowerShell in a normal, minimized, or maximized window.
- Autostart: If you use PowerShell every day, it makes sense to Autostart the application. Then, when Windows starts up it will automatically launch the PowerShell window, and all you have to do to bring it up is to click on its window button on the taskbar. To set up a PowerShell autostart, on the Programs menu of your start menu open the Windows PowerShell 1.0 program folder and right-click on Windows PowerShell. On the context menu, select Copy. Next, right-click on a blank area of your folder and select paste on the context menu. This will place a PowerShell shortcut in the folder. All you have to do now is click on the shortcut with the right button of your mouse and choose Properties. Specify the window size as Minimized.
Here is a special note for Vista users: The default settings of Windows Vista start all programs without administrator privileges. This applies to the PowerShell console as well. So even if you have administrator privileges, you will initially have no access to your administrator rights when using the PowerShell console. That's a new security feature that does make sense. You'd be surprised to see how many routine tasks can be performed without these powerful (and potentially dangerous) rights.
If you need more privileges because commands aren't working right or your system complains about lacking administrator rights, then request your full administrator privileges. To do so, right-click on the PowerShell entry on your start menu and select Run As Administrator on the context menu. The PowerShell console window won't show by default whether you have enabled full administrator privileges, but you can add that feature later (see Chapter 9).
If you'd like to always launch PowerShell with full administrator privileges, click on the shortcut on the start menu with the right button of your mouse and choose Properties. Then click below right on Advanced and activate the option Run As Administrator.
Figure 1.1: Always open PowerShell with administrator rights.
(Run without administrative priveleges whenever possible)
First Steps with the Console
After PowerShell starts, its console window opens, and you see a blinking text prompt, asking for your input. No icons or menus. PowerShell is a command console and almost entirely operated via keyboard input. The prompt begins with "PS" and after it is the path name of the directory where you are located. Start by trying out a few commands. For example, type:
As soon as you press (Enter), your entry will be sent to PowerShell. Because PowerShell has never heard of the command "hello" you will be confronted with an error message highlighted in red.
Figure 1.2: First commands in the PowerShell console
For example, if you'd like to see which files and folders are in your current directory, then type dir (Enter). You'll get a text listing of all the files in the directory PowerShell's communication with you is always text-based. PowerShell can do much more than display simple directory lists. Just pick a different command. The next one provides a list of all running processes:
PowerShell's advantage is its tremendous flexibility. It allows you to control and display nearly all the information and operations on your computer. The command cls allows you to close the console window and the exit command ends PowerShell.
Incomplete and Multiline Entries
Whenever you enter something PowerShell cannot understand, you get a red error message, explaining what went wrong. If you enter something, however, that isn't wrong but incomplete (like a string with one missing closing quote), PowerShell gives you a chance to complete your input. You then see a double-prompt (">>"), and once you completed the line and pressed ENTER twice, PowerShell executes the command. You can also bail out at any time and cancel the current command or input by pressing: (Ctrl)+(C).
The "incomplete input" prompt will also appear when you enter an incomplete arithmetic problem like this one:
>> 2 + (Enter)
>> 6 (Enter)
>> (Enter)8
This feature enables you to make multiline PowerShell entries:
>> "This is my multiline entry.(Enter)
>> I'm now writing a text of several lines (Enter)
>> And I'll keep on writing until it's no longer fun."(Enter)
>> (Enter)This is my little multiline entry.
I'm now writing a text of several lines
And I'll keep on writing until it's no longer fun.
The continuation prompt generally takes its cue from initial and terminal characters like open and closed brackets or quotation marks at both ends of a text string. As long as the symmetry of these characters is incorrect, you'll continue to see the prompt. But you can activate it even in other cases:
>> dir `(Enter)
>> -recurse(Enter)
>>(Enter)
So, if the last character of a line is what is called a "Backtick" character, the line will be continued. You can retrieve that special character by pressing (`)
Important Keyboard Shortcuts
Since everything in PowerShell is keyboard-based, shortcuts are important. By pressing the keys (arrow left) and (arrow right), for example, you can move the blinking cursor to the left or right. Use it to go back and correct a typo. If you want to move the cursor word by word, hold down (Ctrl) while pressing the arrow keys. To place the cursor at the beginning of a line, hit (Home). Pressing (end) will send the cursor to the end of a line.
If you haven't entered anything, then the cursor won't move. It'll move only within entered text. There's one exception: if you've already entered a line and pressed (Enter) to execute the line, you can make this line appear again character-by-character by pressing (arrow right).
Deleting Incorrect Entries
If you've mistyped something, press (backspace) to delete the character to the left of the blinking cursor. (del) erases the character to the right of the cursor. And you can use (esc) to delete your entire current line.
The hotkey (Ctrl)+(Home) works more selectively: it deletes all the characters at the current position up to the beginning of the line. Characters to the right of the current position (if there are any) remain intact. (Ctrl)+(End) does it the other way around and deletes everything from the current position up to the end of the line. Both combinations are useful only after you've pressed (arrow left) to move the cursor to the middle of a line, that is, when text is both to the left and to the right of the cursor.
Overtype Mode
If you enter new characters and they overwrite existing characters, then you know you are in typeover mode. By pressing (Insert) you can switch between insert and typeover modes. The default input mode depends on the console settings you select. You'll learn more about console settings soon.
Command History: Reusing Entered Commands
You don't have to re-type commands, for example to edit them. Simply press (arrow up) to re-display the command that you entered. Press (arrow up) and (arrow down) to scroll up and down your command history. Using (F5) and (F8) do the same as the up and down arrow keys.
This command history feature is extremely useful. Later you'll learn how to configure the number of commands the console "remembers". The default setting is the last 50 commands. You can display all the commands in your history by pressing (F7) and then scrolling up and down the list to select commands using (arrow up) and (arrow down) and (enter).
The numbers before the commands in the Command History list only denote the sequence number. You cannot enter a number to select the associated command. What you can do is move up and down the list by hitting the arrow keys.
To 'activate' the numbers so that you can select a command by its number simply press (F9). This opens a menu that accepts the numbers and returns the desired command.
The keyboard sequence (Alt)+(F7) will clear the command history and start you off with a new list.
(F8) provides more functionality than (arrow up); it doesn't just show the last command you entered but keeps a record of the characters you've already typed in. If, for example, you'd like to see all the commands you've entered that begin with "d", type:
Press (F8) several times. Every time you press a key another command will be displayed from the command history provided that you've already typed in commands with an initial "d."
Automatically Completing Input
An especially important key is (Tab). It will save you a great deal of typing (and typing errors). When you press this key, PowerShell will attempt to complete your input automatically. For example type:
The command cd changes the directory in which you are currently working. Put at least one space behind the command and then press (Tab). PowerShell suggests a subdirectory. Press (Tab) again in order to see other suggestions. If (Tab) doesn't come up with any suggestions, then there probably aren't any subdirectories available.
This feature is called AutoComplete. AutoComplete works in many places. For example, you just learned how to use the command get-process, which lists all running processes. If you want to know what other commands there are that begin with "get-", then type:
Just make sure that there's no space before the cursor when you press (Tab). Keep hitting (Tab) to see all the commands that begin with "get-".
A more complete review of the AutoComplete feature is available in Chapter 9.
AutoComplete works really well with long path names that require a lot of typing. For example:
Every time you press (Tab), PowerShell will prompt you with a new directory or a new file that begins with "c:\p." So, the more characters you type, the fewer options there will be. In practice, you should type at least four or five characters to reduce the number of suggestions.
When the list of suggestions is long, it can take a second or two until PowerShell has compiled all the possible suggestions and displays the first one.
Wildcards are allowed in path names. For example, if you enter c:\pr*e (Tab) in a typical Windows system, PowerShell will respond with "c:\Program Files".
If the response contains whitespace characters, PowerShell will automatically put the entire response inside double quotation marks.
Scrolling Console Contents
The visible part of your console depends on the size of your console window. You change the size of the console window with your mouse: drag the window border while holding down your left mouse button until the window is the size you want. Note that the actual contents of the console, the "screen buffer," doesn't change. If the window is too small to show everything, use the scroll bars.
Selecting and Inserting Text
If you'd like to selecttext inside the PowerShell window and to copy it to the clipboard, use your mouse. Move the mouse pointer to the beginning of the selected text, hold down the left mouse button and drag it over the text area that you want to mark.
QuickEdit Mode
QuickEdit is the default mode for selecting and copying text in PowerShell. Select the text using your mouse and PowerShell will highlight it. After you've selected the text, press (Enter) or right click on the marked area. This will copy the selected text to the clipboard. You can now paste it into other applications. To unselect press (Esc).
You can also insert the text in your console at the blinking command line by right clicking your mouse.
Figure 1.3: Marking and copying text areas in QuickEdit mode
Standard Mode
If QuickEdit is turned off and you are in 'Standard' mode, the simplest way to mark and copy text is to right-click in the console window. If QuickEdit is turned off, a context menu will open.
Select Select if you want to mark text, and select Paste if you want to insert the marked text (or other text contents that you've copied to the clipboard) in the console.
It's usually more practical to activate QuickEdit mode so that you won't have to use to the context menu.
Customizing the Console
You can customize a variety of settings in the console including edit mode, screen buffer size, font colors, font sized, etc.
Opening Console Properties
The basic settings of your PowerShell console are configured in a special Properties dialog box. To open it, click on the PowerShell icon on the far left of the title bar of the console window.
Figure 1.4: Opening console properties
That will open a context menu. Select Properties. The Properties dialog box opens.
To get help, click on the question mark button on the title bar of the window. A question mark is then pinned to your mouse pointer. Next, click on the option you need help for. The help appears as a ScreenTip window.
Defining Options
Under the heading Options are four panels of options:
Figure 1.5: Defining the QuickEdit and Insert modes
- Edit options: You should select the QuickEdit mode as well as insert mode. We've already discussed the advantages of the QuickEdit mode: it makes it much easier to select, copy, and insert text. The insert mode makes sure that new characters don't overwrite existing input. So when you're editing command lines, new characters will be added without erasing text you've already typed in.
- Cursor size: here you specify how large the blinking cursor is going to be.
- Display options: determine whether the console should be displayed as a window or full screen. The "window" option is best so that you can easily switch to other windows when you're working. The full screen display option is not available on all operating systems.
- Command history: here you can choose how many command inputs the console "remembers". This allows you to select a command from the list by pressing (arrow up) or (F7). The option Discard Old Duplicates ensures that the list doesn't have any duplicate entries. Soif you enter one command twice, it will appear only once in the history list.
Specifying Fonts and Font Sizes
On the Font tab, you can choose both the font and the font size displayed in the console.
The console often uses the raster font as its default. This font is available in a specific range of sizes; available sizes are shown in the "Size" list. Scalable TrueType fonts are more flexible. They're marked in the list by a "TT" symbol. When you select a TrueType font, you can choose any size in the size list or enter them as text in the text box. TrueType fonts can be dynamically scaled.
Figure 1.6: Specifying new fonts and font sizes
Also try experimenting with TrueType fonts by using the "bold fonts" option. TrueType fonts are often more readable when they're displayed in bold.
The choice of fonts may at first seem a bit limited. To get more font choices, you can add them to the console font list. The limited default font list is supposed to prevent you from choosing unsuitable fonts for your console.
One reason for this is that the console always uses the same width for each character (fixed width fonts). This restricts the use of most Windows fonts because they're proportional typefaces: every character has its own width; an "i," for example, is narrower than an "m." If you're sure that a certain font will work in the console, then here's how to add the font to the console font list:
Open your registry editor. In the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont insert a new "string value" and give this entry the name "00" (numbers, not letters).
If there's already an entry that has this name, then call the new entry "000" or add as many zeroes as required to avoid conflicts with existing entries. Then double-click your new entry to open it and enter the name of the font. The name must be exactly the same as the official font name, just the way it's stated under the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts.
The newly added font will now show up in the console's option field. However the new font will work only after you either logged off at least once or restarted your computer. If you don't, the console will simply ignore your new font when you select it in the dialog box.
Setting Window and Buffer Size
On the Layout tab, you specify how large the screen buffer should be, that is, how much information the console should "remember" and how far back you can scroll with the scroll bars.
Select a width of at least 120 characters in the window buffer size area. The height should be at least 1000 lines, but it can be much larger. This gives you the opportunity to use the scroll bars to scroll the window contents back upwards so that you can look at all the results of your previous commands.
Figure 1.7: Specifying the size of the window buffer
You can also set the window size and position on this tab if you'd like your console to open at a certain size and at a certain screen position on your display. Choose the option Let system position window and the Windows will automatically determine at what location the console window will open.
Selecting Colors
On the Colors tab you can select your own colors for four areas:
- Screen text: console font
- Screen background: console background color
- Popup text: popup window font, for example, command history's (F7)
- Popup background: popup window background color
You have a palette of 16 colors for these four areas. So, if you want to specify a new font color, first select the option Screen Text and click on one of the 16 colors. If you don't like any of the 16 colors, then mix your own special shade of color. Just click on a palette color and choose your desired color value at the upper right from the primary colors red, green, and blue.
Figure 1.8: Select better colors for your console
Directly Assigning Modifications in PowerShell
Some of the console configuration can also be done from within PowerShell code. You'll hear more about this later. To give you a quick impression, take a look at this:
$host.ui.rawui (Enter)
$host.ui.rawui.ForegroundColor = "Yellow" (Enter)
$host.ui.rawui.WindowTitle = "My Console" (Enter)
These changes will only be temporary, and once you close and re-open PowerShell, the changes are gone. To make them permanent, you'd have to include these lines into one of your "profile scripts" which run every time you launch PowerShell. You can read more about this in Chapter 10.
Saving Changes
If you've successfully configured all your settings in the dialog box, close the dialog box. If you're using Windows Vista, all changes will be saved immediately, and when you start PowerShell the next time, your new settings will be in effect. You may need Admin rights to save settings if you launched PowerShell with a link in your startmenu that applies for all users.
If you're using Windows XP, you'll see an additional window and a message asking you whether you want to save changes just for now (Apply properties to current window only) or permanently (Modify shortcut that started this window).
Piping and Routing
Since some commands output a lot of information, you may want to view the information page by page or save it in a file.
Piping: Outputting Information Page by Page
The pipe command more outputs information screen page by screen page. You need to press a button (like space) to continue to the next page.
Piping uses the vertical bar (|). The results of the command to the left of the pipe symbol are then fed into the command on the right side of the pipe symbol:
Get-process | more (Enter)
Pressing (Ctrl)+(C) will stop output. This pipe command also works with other commands and for other purposes. Piping works for all kinds of commands, not just more. If you'd rather like to get a sorted directory listing, pipe the result to sort-object and specify the columns you would like to sort:
dir | sort-object -Property length, Name (Enter)
You'll find more background information on piping as well as many useful examples in Chapter 5.
Redirecting: Storing Information in Files
If you'd like to redirect the result of a command to a file, use the redirection symbol ">":
The information won't appear in the console but instead is redirected to the specified file. You can then open the file.
However, opening a file in PowerShell is different from the opening a file in the classic console:
help.txt (Enter)
The term "help.txt" is not recognized as a cmdlet, function,
operable program, or script file. Verify the term and try again.
At line:1 character:8
+ help.txt <<<<
If you only specify the file name, PowerShell will look for it in all folders listed in the PATH environment variable. So to open a file, you have to specify its absolute or relative path name, for example:
Or, to make it even simpler use AutoComplete and hit (Tab) after the file name:
The file name will automatically be completed with the absolute path name, and then you can open it by pressing (Enter):
& "C:\Users\UserA\help.txt" (Enter)
You can also append data to an existing file. For example, if you'd like to supplement the help information in the file with help on native commands, attach this information to the existing file with the redirection symbol ">>":
Cmd /c help >> help.txt (Enter)
If you'd like to directly process the result of a command, you won't need traditional redirection at all because PowerShell can also store the result of any command to a variable:
$result = Ping 10.10.10.10
$result
Answer from 10.10.10.10: bytes=32 Time<1ms TTL=128
Answer from 10.10.10.10: bytes=32 Time<1ms TTL=128
Answer from 10.10.10.10: bytes=32 Time<1ms TTL=128
Answer from 10.10.10.10: bytes=32 Time<1ms TTL=128
Ping statistics for 10.10.10.10:
Packets: transmitted = 4, received = 4, lost = 0 (0% loss),
Ca. time in millisec.:
Minimum = oms, Maximum = oms, Mittelwert = 0ms
Variables are universal data storage. Variable names always start with a "$". You'll find out more about variables in Chapter 3.
Summary
PowerShell is an optional component for Windows XP and better. Before you can use PowerShell, you will have to download and install it. Beginning with Windows Server 2008, PowerShell is included with Windows by default. It still needs to be enabled in Windows software feature list. You find PowerShell, like any other program, in the start menu below "All Programs." It is located in the program folder Windows PowerShell 1.0. The program file name is "powershell.exe."
PowerShell is a basic console program which heavily relies on text input and doesn't use icons or mouse. There are plenty of special keys listed in Table 1.1.
| Key |
Meaning |
| (Alt)+(F7) |
Deletes the current command history |
| (PgUp), (PgDn) |
Display the first (PgUp) or last (PgDn) command you used in current session |
| (Enter) |
Send the entered lines to PowerShell for execution |
| (End) |
Moves the editing cursor to the end of the command line |
| (Del) |
Deletes the character to the right of the insertion point |
| (Esc) |
Deletes current command line |
| (F2) |
Moves in current command line to the next character corresponding to specified character |
| (F4) |
Deletes all characters to the right of the insertion point up to specified character |
| (F7) |
Displays last entered commands in a dialog box |
| (F8) |
Displays commands from command history beginning with the character that you already entered in the command line |
| (F9) |
Opens a dialog box in which you can enter the number of a command from your command history to return the command. (F7) displays numbers of commands in command history |
| (Left arrow), (Right arrow) |
Move one character to the left or right respectively |
| (Arrow up) , (Arrow down) , (F5), (F8) |
Repeat the last previously entered command |
| (Home) |
Moves editing cursor to beginning of command line |
| (Backspace) |
Deletes character to the left of the insertion point |
| (Ctrl)+(C) |
Cancels command execution |
| (Ctrl)+(End) |
Deletes all characters from current position to end of command line |
| (Ctrl)+(Arrow left), (Ctrl)+(Arrow right) |
Move insertion point one word to the left or right respectively |
| (Ctrl)+(Home) |
Deletes all characters of current position up to beginning of command line |
| (Tab) |
Automatically completes current entry, if possible |
Table 1.1: Important keys and their meaning in the PowerShell console
The keys (arrow up), which repeats the last command, and (Tab), which completes the current entry are particularly useful. By hitting (Enter), you complete an entry and send it to PowerShell. If PowerShell can't understand a command, an error message appears highlighted in red stating possible reasons for the error. Two special commands are cls (deletes the contents of the console) and exit (ends PowerShell).
You can use your mouse to select information in the console and copy it to the Clipboard by pressing (Enter) or by right-clicking when the QuickEdit mode is turned on. With QuickEdit mode turned off, you will have to right-click inside the console and then select Select from a context menu.
The basic settings of the console—QuickEdit mode as well as colors, fonts, and font sizes—can be customized in the properties window of the console. This can be accessed by right-clicking the icon to the far left in the title bar of the console window. In the dialog box, select Properties.
Along with the commands, a number of characters in the console have special meanings; you have already become acquainted with three of them:
- Piping: the vertical bar "|" symbol pipes the results of a command to the next. When you pipe the results to the command more, the screen output will be paused once the screen is full, and continued when you press a key.
- Redirection: the symbol ">" redirects the results of a command to a file. You can then open and view the file contents. The symbol ">>" appends information to an existing file.
Posted
Oct 20 2008, 02:00 AM
by
ps1