Test-Driving Scripts without Aliases

by Jul 18, 2014

All PowerShell versions

Aliases can be cool in interactive PowerShell but should not be used in scripts. In scripts, use the underlying commands (so use “Get-ChildItem” instead of “dir” or “ls”).

To test drive a script, you can delete all aliases and then try and see if your script still runs. This is how you’d delete all aliases for the particular PowerShell session (it won’t affect other PowerShell sessions and will not delete built-in aliases permanently).

PS> Get-Alias |
ForEach-Object { Remove-Item -Path ("Alias:\" + $_.Name) -Force }

PS> dir


dir : The term 'dir' is not recognized as the name of a cmdlet,
function, script file, or operable
program. Check the spelling of
the name, or if a path was included, verify that the path is correct
and try again.
At line:1 char:1
+ dir
+ ~~~
    + CategoryInfo         
: ObjectNotFound: (dir:String) [], CommandNotFoundException
    + FullyQualifiedErrorId :
CommandNotFoundException
 


PS> Get-Alias
 

As you see, all aliases are cleaned out, and if a script now uses an alias, it will raise an exception. Once you close and restart PowerShell, all built-in aliases are restored.

Twitter This Tip! ReTweet this Tip!