Section 2.2. Save Keystrokes with Aliases


2.2. Save Keystrokes with Aliases

Isn't it odd that cd, dir, and echo still work in MSH? These commands don't follow the regular verb-noun format for cmdlets, yet MSH will happily work with them. This is an example of aliases at work. An alias is a mapping from one string to another, usually used to map a short name to any longer name for convenience.

When running the dir command, MSH is silently translating it to get-childitem (the equivalent cmdlet) and running that instead. This feature helps to shorten command length (and keystrokes) and bridge the syntax gap for the transition to MSH.

It's easy to set up your own aliases for commonly used commands.

A Word of Caution

Aliases can be a remarkably effective way of obscuring the behavior of a command or script, so it should be used sparingly. While it's certainly true that once you've defined a few aliases it's quier to type gps | so | ms | fl, do think of others (and yourself!) in the position of trying to understand exactly what's going on.

Although aliases are great for saving keystrokes, heavy use of very specific aliases within a script can render it less portable. If the functioning of a script depends on a whole list of custom alias mappings to be in place, it may be more difficult to transfer the script to other machines or share it with others without a long set-alias sequence at the start.

Using full cmdlet names (in long verb-noun format) is a good habit to get into and, as hard as it may be, leaving behind the legacy aliases such as dir, ls, and ps will help to make your scripts more universally readable.


2.2.1. How Do I Do That?

Let's start by taking a look at the default aliases . With no parameters, the get-alias cmdlet lists all active aliases:

     MSH D:\MshScripts> get-alias     CommandType     Name                            Definition     -----------     ----                            ----------     Alias           ac                              add-content     Alias           clc                             clear-content     Alias           cli                             clear-item     Alias           clp                             clear-property     Alias           clv                             clear-variable     Alias           cpi                             copy-item     Alias           cpp                             copy-property     Alias           cvpa                            convert-path     Alias           epal                            export-alias     Alias           epcsv                           export-csv     Alias           fc                              format-custom     Alias           fl                              format-list     Alias           foreach                         foreach-object     Alias           ft                              format-table     Alias           fw                              format-wide     Alias           gal                             get-     ...

That's quite a list. If we're just interested in finding out what the echo alias actually maps to, we can pass an alias to get-alias to single out only that mapping:

     MSH D:\MshScripts> get-alias echo     CommandType    Name                      Definition     -----------    ----                      ----------     Alias          echo                      write-object

The set-alias cmdlet is used to create mappings, and it takes two parameters: first the alias and second the arbitrary target name. Maybe echo is still too many keystrokes and we'd prefer something more concise:

     MSH D:\MshScripts> set-alias e write-object     MSH D:\MshScripts> e "Hello, World!"     "Hello, World!"

2.2.2. What Just Happened?

MSH stores its alias mappings in a simple lookup table that translates one string to another. When run, MSH first looks at a command for any aliases and then replaces them with their corresponding target. After that step is complete, MSH then looks for cmdlets, functions, and other shell constructs that are necessary to execute the command.

It's perfectly valid for aliases to take the same verb-noun form as cmdlets. Indeed, this can prove useful when overriding a cmdlet or rewiring the default verb. As we've seen, if a cmdlet is invoked without a verb, the get action is assumed. This behavior isn't always desired. For example, the location command could be used to set the location, instead of returning it, by defining set-alias location set-location.

Aliases can refer to other aliases or functions; after all, they're just a mapping from one string to another. It's also possible for an alias to refer to a nonexistent target; in such cases, you won't find out about any alias-mapping problems until you try to use it.

MSH doesn't check whether your alias is meaningful. A mistake in the set-alias statement might go undetected until you try to invoke it, so make sure an alias works as expected before depending on it.


As an alias can only point to one target at a time, the set-alias cmdlet will overwrite any previous alias mapping. It's possible to remove user-defined aliases from the mapping table with the remove-item alias:myalias command, although the built-in aliases such as gps (for get-process) cannot be changed. The built-in aliases are set up when the shell starts and will always be available. To get the list of constant aliases , use the following command:

     MSH D:\MshScripts> get-alias | where-object { $_.Options -band     [System.Management.Automation.ScopedItemOptions]::Constant }

Because names for files, aliases, cmdlets, and other programs can potentially overlap, MSH follows a strict sequence of evaluation to determine what it's meant to do. The following order is used:


Alias

Alias replacement occurs first, as previously described.


Function/filter

We'll look at functions further in Chapter 3.


Cmdlet

Cmdlets are the last internal command type in the shell to be checked.


Scripts

If none of the previous three makes a match, MSH looks for scripts (with extension .msh) in the directories in the %PATH% environment variable.


Other programs

If none of the previous four makes a match, MSH again looks through the directories in the %PATH% environment variable for any file with an extension defined in the %PATHEXT% environment variable. Generally, this includes .com, .exe, .bat, .cmd, and a few other file types like those used by cmd.exe.

In a typical configuration, the current directory is not included in the path. Therefore, scripts and other programs might not be found, even if the current working directory contains a script or executable file with a matching name.


2.2.3. What About...

...Including parameters in the alias definition? There are plenty of cases where it would be convenient for an alias to refer to another command and pre-fill some of its parameters. For example, suppose I want to define an archive alias that used the copy-item cmdlet but always prepopulates the target folder. Aliases are simple in their design and cannot be used for this; they're a mechanism for bringing speed and/or consistency to command invocation. However, another MSH feature, functions, can be used to solve this need and many more. We'll look at functions in the next chapter.

...Can multiple aliases point at the same cmdlet? They can. If you'd rather use displaytext to insert objects into the pipeline, feel free to create an alias for it. Either alias displaytext write-object or alias displaytext echo would work well.

...Finding out which aliases refer to a given cmdlet? The get-alias cmdlet puts the shell alias table into the pipeline. We can use the trusty where-object to filter the mappings to just look for those that we're interested in. For example, we've seen a lot of get-process so far, so let's see whether the profile defines any aliases for it:

     MSH D:\MshScripts> get-alias | where-object {$_.Definition -eq "get-process"}     Command Type    Name                      Definition     ------------    ----                      ----------     Alias           gps                       get-process     Alias           ps                        get-process

Can aliases be used in a script? Aliases are available throughout the shell and work just as well in a script as elsewhere. However, it's important to realize that the use of aliases can potentially make scripts less portable. If a script relying on a certain alias is taken to a different machine or run by a different user, it's not guaranteed that the mapping will be in place, and the script may fail. As MSH moves away from legacy aliases, such as dir and cd, it's a good idea to get into the habit of using the long form of the cmdlet name in scripts.

2.2.4. Where Can I Learn More?

The get-command cmdlet can be used with a command-line option -Noun as in get-command -noun alias to return a list of alias-related cmdlets. As always, get-help provides more information about the complete usage of these cmdlets.




Monad Jumpstart
Monad Jumpstart
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 117

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net