
close
close
Efficiency is paramount when working with the PowerShell console to get work done. Because there’s a lot of typing involved when working with PowerShell, there’s several features that intend to limit typing, such as tab completion for command and parameter names. Another ease-of-use feature is the PowerShell alias. Instead of typing Get-WmiObject, you can type a shortcut, gwmi. There’s nothing wrong with that. When it comes time to writing a script, however, the best practice is to use full cmdlet and parameter names. Another use of aliases is as transition-aids, which is demonstrated by using dir instead of having to use Get-ChildItem.
PowerShell automatically defines many aliases whenever you start a new session. You can also create your own aliases. You might do this for your own functions or even command-line tools. In my PowerShell profile, I have a command like this:
pre class=”EnlighterJSRAW” data-enlighter-language=”generic”>Set-alias –name np –value notepad.exe
At any time, I can type np and Notepad will launch. My PowerShell profile has grown over the years, and it has been moved around as I have changed computers. Recently I realized I had some aliases that were pointing to items that no longer existed. It doesn’t really matter if you have orphaned aliases, but I like things neat, so I decided that I needed a tool to test if an alias was still valid. I can use the Get-Alias cmdlet to get details.
Using get-alias to get details in Windows PowerShell. (Image Credit: Jeff Hicks)
$a = Get-alias np
get-command -Name $a.Definition
Using get-command in Windows PowerShell. (Image Credit: Jeff Hicks)
set-alias -name foo -value c:\windows\system32\foobar.exe
Creating an alias in Windows PowerShell. (Image Credit: Jeff Hicks)
Testing the backing command in Windows PowerShell. (Image Credit: Jeff Hicks)
Try { $c = Get-Command $b.Definition -erroraction Stop;$True} Catch { $false}
Using our try-catch statement for our alias. (Image Credit: Jeff Hicks)
#requires -version 4.0 Function Test-Alias { <# .Synopsis Test if an alias is valid. .Description Use this command to verify that an alias is pointing to a command that still exists. Use -Quiet to get only a True/False result. NOTE: Using this command will have a side-effect of importing associated modules. If the alias points to a command in a PSSnapin, you will get an incorrect result unless you add the PSSnapin first. .Parameter Name The alias name. You can pipe Get-Alias to this command. .Parameter Quiet Only display True or False. .Example PS C:\> test-alias gsv,ps,foo,np | format-table -AutoSize Name Definition Test ---- ---------- ---- gsv Get-Service True ps Get-Process True foo x False np C:\windows\notepad.exe True .Example PS C:\> get-alias | test-alias | where {! $_.Test} | format-table -AutoSize Name Definition Test ---- ---------- ---- chr C:\Users\Jeff\AppData\Local\Google\Chrome\Application\chrome.exe False foo x False pe G:\sysinternals\procexp.exe False TryMe Get-Foo False Find aliases that won't work. .Example PS C:\> test-alias gci -quiet True A simple boolean test .Notes Last Updated: 4/2/2015 Version : 1.0 Learn more about PowerShell:Essential PowerShell Learning Resources**************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** .Link Get-Alias Get-Command .Inputs [string] .Outputs [Boolean] [PSCustomObject] #> [cmdletbinding()] Param( [Parameter(Position=0,Mandatory,HelpMessage="Enter the name of an alias", ValueFromPipeline,ValueFromPipelineByPropertyName)] [ValidateNotNullorEmpty()] [string[]]$Name, [switch]$Quiet ) Begin { Write-Verbose "Starting $($MyInvocation.Mycommand)" } #begin Process { foreach ($alias in $Name) { Write-Verbose "Testing alias : $alias" Try { $def = (Get-Alias -Name $alias -ErrorAction Stop).Definition } Catch { Write-Warning "No alias found called $alias" } if ($def) { Try { Write-Verbose "Verifying command: $def" if (Get-Command -Name $def -erroraction Stop) { $tested = $True } } Catch { $tested = $False } if ($Quiet) { Write $tested } else { #write a custom object to the pipeline [pscustomobject]@{ Name = $alias Definition = $def Test = $Tested } } #clear $def so it doesn't get accidentally re-used Remove-Variable -Name Def } #if $def } #foreach } #process End { Write-Verbose "Ending $($MyInvocation.Mycommand)" } #end } #end Test-Alias #create an alias Set-Alias -Name ta -Value Test-Alias
Test-Alias Help. (Image Credit: Jeff Hicks)
Testing the alias in PowerShell by name. (Image Credit: Jeff Hicks)
Piping a name to the alias. (Image Credit: Jeff Hicks)
If (test-alias ls) {
#found
}
get-alias | test-alias | where {-Not $_.Test} | format-table –AutoSize
Validating alias from the console. (Image Credit: Jeff Hicks)
advertisment
More from Jeff Hicks
advertisment
Petri Newsletters
Whether it’s Security or Cloud Computing, we have the know-how for you. Sign up for our newsletters here.
advertisment
More in PowerShell
Microsoft’s New PowerShell Crescendo Tool Facilitates Native Command-Line Wraps
Mar 21, 2022 | Rabia Noureen
Most popular on petri
Log in to save content to your profile.
Article saved!
Access saved content from your profile page. View Saved
Join The Conversation
Create a free account today to participate in forum conversations, comment on posts and more.
Copyright ©2019 BWW Media Group