Getting Started with PowerShell
上QQ阅读APP看书,第一时间看更新

PowerShell aliases

If you tried to use DIR and CD in the last section, you may have noticed that they didn't work exactly as the DOS commands that they resemble. In case you didn't see this, enter DIR /S on a PowerShell prompt and see what happens. You will either get an error complaining about a path not existing, or get a listing of a directory called S. Either way, it's not the listing of files including subdirectories. Similarly, you might have noticed that CD in PowerShell allows you to switch between drives without using the /D option and even lets you change to a UNC path. The point is that, these are not DOS commands. What you're seeing is a PowerShell alias.

Aliases in PowerShell are alternate names that PowerShell uses for both PowerShell commands and programs. For instance, in PowerShell, DIR is actually an alias for the Get-ChildItem cmdlet. The CD alias points to the Set-Location cmdlet. Aliases exist for many of the cmdlets that perform operations similar to the commands in DOS, Linux, or Unix shells. Aliases serve two main purposes in PowerShell, as follows:

  • They allow more concise code on Command Prompt
  • They ease users' transition from other shells to PowerShell

To see a list of all the aliases defined in PowerShell, you can use the Get-Alias cmdlet. To find what an alias references, type Get-Alias <alias>. For example, see the following screenshot:

PowerShell aliases

To find out what aliases exist for a cmdlet, type Get-Alias –Definition <cmdlet> as follows:

PowerShell aliases

Here we can see that the Get-ChildItem cmdlet has three aliases. The first and last assist in transitioning from DOS and Linux shells, and the middle one is an abbreviation using the first letters in the name of the cmdlet.