In PowerShell, an alias is another name assigned to a cmdlet, function, script, executable file, and so on. Just about...
User-Defined PowerShell Aliases
Syntax to create User-defined alias:
Set-Alias alias command
Set-Alias gs Get-Service <enter>
Test the new Alias:
When you close the powershell session and in the new session when you type gs you get the following error:
If we want to create a user defined alias and want to use it for ever then we can do the follwoing:
Import/Export User-Defined PowerShell Aliases
The reason for Importing and Exporting is to make user-defined aliases available to multiple different machines. creating a script that uses custom aliases and attempting to run the script on another machine would fail. The remote PowerShell session is not aware of the custom aliases that have been created.
To make it work you have to export the aliases to a text file and import it on the remote computer.
To export the alias use the following command:
Export-Alias -Path Aliases.txt <enter>
Since in the current example the home directory is H:\myprofile\MyScritps> the aliases.txt file is saved at this location.
To open the aliases.txt file in notepad:
PS H:\myprofile\MyScritps>notepad Aliases.txt <enter>
you will notice that alogn with user-defined alias “gs” all Powershell built in aliases are also exported. once we try to import this aliases.txt file then powershell will throw an error for the aliases that already exists.
To export just the alias that you created we can use -Name parameter
Export-Alias -Path Aliases.txt -Name gs <enter>
To import Aliases.txt file use the following command:
Import-Alias -Path Aliases.txt <enter> gs <enter>
Importing and Exporting allows for the use of user-defined aliases on local and multiple systems.
if you just wanted to use custom aliases on your local system and don’t want to import a file each time you launch PowerShell then we can user powershell profiles. We will discuss profiles in the next blog.