Command aliases
Throughout this book and previous books, we have referred to command aliases or cmdlet aliases: for example, the short name of the full cmdlet.
These aliases can be very handy when writing scripts where you might want to optimize and keep them as small and as short as possible.
Let us take a look at some examples of the built-in aliases. For example, we have the cmdlet Where-Object
, which is commonly used. We have two aliases for it, which are? or where. Another example on a regularly used cmdlet would be ForEach-Object
; there are two aliases for it and those are %
or foreach
. The last example of a built-in alias is for the cmdlet Select-Object
, where the alias is select
.
How to do it...
When running a PowerShell command, instead of using the full cmdlet, we can create aliases for them. Let's have a look at a few examples of how to utilize the aliases:
Get-Alias New-Alias -Name wh -Value Write-Host wh "Testing alias" New-Alias -Name list -Value Get-ChildItem list -Path "C:\Scripts" New-Alias -Name npp -Value "C:\Program Files ` (x86)\Notepad++\notepad++.exe" npp
How it works...
We start off with using the Get-Alias
cmdlet. With the cmdlet, we will list all current aliases. If you haven't created any custom aliases only the built-in aliases are listed.
In the preceding examples, we have three different aliases created. Aliases could be created for cmdlets that you are using frequently or if you want to be able to launch an application using an alias directly from the PowerShell prompt.
The first example is set to wh
, which is an alias for Write-Host
. We can use this by type in wh "Testing alias"
, and the Write-Host cmdlet should be utilized in the background and show us the text on screen.
In our second example, we have to create an alias for Get-ChildItem
; the alias we create for it is list
. We can then get started to use list -Path "C:\Scripts"
to retrieve all the files and folders from the folder C:\Scripts
.
The third and final example is to create an alias for launching the Notepad++ application. This is simply done by setting the value of the alias to the full path to the .exe file of the application. Once it's done, you can from the PowerShell prompt, you can simply type in npp
for launching Notepad++.
See also
- The Setting up a PowerShell profile recipe in this chapter
- The Working with variables and objects recipe in this chapter
- The Looping through items recipe in this chapter