I picked up Jerry Lee Ford’s book Microsoft Windows PowerShell Programming for the absolute beginner .
In the section on aliases, he warns users that Set-Alias does not verify the validity of the alias assignment. That is a good point. Here is a function that does that for you.
function Set-Alias-Strict($Name, $Value)
{
$null = Get-Command $Value
Set-Alias $Name $Value
}
Set-Alias sals Set-Alias-Strict
Here is that function in action:
PS> Set-Alias test Get-Porcess
PS> Set-Alias-Strict test Get-Porcess
Get-Command : The term ‘Get-Porcess’ is not recognized as a cmdlet, functio
n, operable program, or script file. Verify the term and try again.
At line:3 char:24
+ $null = Get-Command <<<< $Value
PS> Set-Alias-Strict test Get-Process
PS>
I transpose characters on a fairly frequent basis so this is a good thing for me to use. Of course I don’t want to type all that so the alias comes in handy:
PS> sals test Get-Porcess
Get-Command : The term ‘Get-Porcess’ is not recognized as a cmdlet, functio
n, operable program, or script file. Verify the term and try again.
At line:3 char:24
+ $null = Get-Command <<<< $Value
PS> sals test Get-Process
PS>
Notice the naming model I used. If there is a command that doesn’t have the functions you want it to have, I recommend the naming scheme here (this was first suggested by Lee Holmes). Create a new name by taking the old name and concatenating a “-” and a word. (e.g. “-Strict” ). This makes it easier to find and understand.
PS> gcm *-alias*
CommandType Name Definition
———– —- ———-
Cmdlet Export-Alias Export-Alias [-Path] <Stri…
Cmdlet Get-Alias Get-Alias [[-Name] <String…
Cmdlet Import-Alias Import-Alias [-Path] <Stri…
Cmdlet New-Alias New-Alias [-Name] <String>…
Cmdlet Set-Alias Set-Alias [-Name] <String>…
Function Set-Alias-Strict param($Name, $Value) $null…
PS>
Enjoy!
Jeffrey Snover [MSFT]
Windows PowerShell/MMC Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx
0 comments