Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a command for checking alias existence in PowerShell?

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.)

like image 238
IbrarMumtaz Avatar asked Jan 03 '14 14:01

IbrarMumtaz


People also ask

How do I view PowerShell aliases?

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.

How do you check path exists or not in PowerShell?

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.

What command will list PowerShell aliases?

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.

Which command will display all the aliases that the system is currently using?

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.


1 Answers

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.

like image 195
Duncan Avatar answered Sep 18 '22 13:09

Duncan