Picture of Rahul NathRahul Nath
  • Home
  • Blog
  • About
Skip to main content

Dynamically Create Powershell Alias

December 10, 2019•2 min read

While playing around with the Windows Terminal, I had set up Aliasing to enable alias for commonly used commands.

For e.g. Typing in s implies git status.

I wanted to create new command aliases from the command line itself, instead of opening up the script file and modifying it manually. So I created a PowerShell function for it.

$aliasFilePath = "<Alias file path>"
function New-CommandAlias {
param(
[parameter(Mandatory=$true)]$CommandName,
[parameter(Mandatory=$true)]$Command,
[parameter(Mandatory=$true)]$CommandAlias
)
$functionFormat = "function $commandName { & $command $args }
New-Alias -Name $commandAlias -Value $commandName -Force -Option AllScope"
$newLine = [Environment]::NewLine
Add-Content -Path $aliasFilePath -Value "$newLine$functionFormat"
}
. $aliasFilePath

The script does override existing alias with the same name. Use the 'Get-Alias' cmdlet to find existing aliases.

The above script writes a new function and maps it to the alias command using the existing New-Alias cmdlet

function Get-GitStatus { & git status -sb $args }
New-Alias -Name s -Value Get-GitStatus -Force -Option AllScope

Add this to your PowerShell profile file (run notepad $PROFILE) as we did for theming when we set up the windows terminal. In the above script, I write to the '$aliasFIlePath' and load all the alias from that file using the Dot sourcing operator.

Below are a few sample usages

New-CommandAlias -CommandName "Get-GitStatus" -Command "git status -sb" -CommandAlias "s"
New-CommandAlias -CommandName "Move-ToWorkFolder" -Command "cd C:\Work\" -CommandAlias "mwf"

The full gist is available here. I have tried adding only a couple of commands, and it did work fine. If you find any issues, please drop a comment.

Tools
Back to Blog

Table of contents

About the author

R

Rahul Nath

Software engineer passionate about AWS, .NET, and building better developer experiences. I write about cloud architecture, productivity, and the lessons learned from over a decade in software development.