Is there a PowerShell command that allows you to check to see if an alias exists or not?
(I have been looking around on the web, and it doesn't look like it.)
The Get-Alias cmdlet gets the aliases in the current session. This includes built-in aliases, aliases that you have set or imported, and aliases that you have added to your PowerShell profile. By default, Get-Alias takes an alias and returns the command name.
The Test-Path cmdlet determines whether all elements of the path exist. It returns $True if all elements exist and $False if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal or leaf element.
The Get-Alias cmdlet displays the aliases available in a PowerShell session. To create an alias, use the cmdlets Set-Alias or New-Alias . In PowerShell 6, to delete an alias, use the Remove-Alias cmdlet.
Invoking alias with the -t option, but without any specified names, displays all currently defined tracked aliases with appropriate quoting. marks each alias name on the command line for export.
You can use Test-Path
for this:
PS C:\> test-path alias:l*
True
PS C:\> test-path alias:list*
False
Just use:
if (Test-Path alias:list*) { ... }
or
if(!(Test-Path alias:list*)) { ... }
if you want to do something when the alias doesn't exist.
As others wrote, Get-Alias
works as well, but Test-Path
will avoid building the list of aliases so might be every so slightly faster if you care about that.
Further explanation:
Powershell uses path names to access a lot more than just files, so while C:
prefix lets you access files on drive C, alias:
lets you access aliases, and other qualifers let you access things like functions, commands, registry keys, security certificates, and so on. So here, alias:l*
is a wildcard pathname which will match all aliases that begin with the letter l
in exactly the same way that C:l*
would match all files beginning with l
in the root of drive C.
Test-Path
is a commandlet which tests whether the path refers to an existing object with a True result only if at least one existing object matches that path. So normally you would use it to test whether a file exists but equally you can test for existence of anything that is addressable with a suitable qualifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With