Sneaky Aliases

I love aliases in PowerShell because they make working in the interactive shell so much easier and faster. I’ve even created aliases for common apps I use like PrimalScript and PrimalForms so I can launch them from PowerShell with a few keystrokes. One drawback to aliases is that you can use them to reference any command that takes parameters. The alias can only substitute for the command. That means I can’t do this:

PS C:\ new-alias -name t -value (get-date -displayhint time)

PowerShell will complain. But there is a sneaky work around. You can alias a function.  All I need to do is wrap the expression in a function and create an alias to that.

PS C:\> function show-time {get-date -displayhint time}
PS C:\> new-alias t show-time
PS C:\> t

11:14:36 AM

PS C:\>

I can add these lines to my profile and presto, I have the alias I want. As you can see, PowerShell functions don’t have to be complicated or long.  In fact I didn’t even have to create a script. You can use this technique in PowerShell v1.0 and the latest PowerShell CTP.