21

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
IbrarMumtaz
  • 4,235
  • 7
  • 44
  • 63
  • As pointed out in @Rhumborl's answer, you can append "-force" to a New-Alias command to prevent an error message from being printed. – Josh Desmond Jul 22 '19 at 16:44

8 Answers8

34

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.

Duncan
  • 92,073
  • 11
  • 122
  • 156
  • 1
    I prefer this solution. When you test for the existence of an alias and the alias does not exists Test-Path does not display a warning message as Get-Alias cmdlet does ('Get-Alias : This command cannot find a matching alias because an alias with the name '\alias-of-the-command' does not exist.') – kri Jul 03 '15 at 12:17
  • 1
    I don't understand anything you said in this answer. – Andrew Nov 02 '17 at 17:59
  • 2
    @Andrew perhaps if you said what it is exactly you don't understand then I could improve the answer? To me it seems that when asked "is there a command for checking alias existence" and I say "you can use `Test-Path` for this" that that is a clear answer but I'm happy to expand on anything which is unclear. – Duncan Nov 03 '17 at 09:09
  • As I said: "**anything**". What's the colon? Why is `test-path` being used here? What is `alias:l*` or `alias:list*`, and why do they return true or false? Why are you putting that in an if statement? I know a lot of programming languages but PowerShell is its own beast and this answer isn't helping me learn it because it explains nothing. – Andrew Nov 03 '17 at 11:55
  • 2
    @Andrew, I added some further explanation, but I agree Powershell can be confusing at first. It is completely unlike any other shell scripting language, because everything you work with are objects rather than text, but equally it is unlike normal programming languages because it's all about commands and pipelines, and in this case the way that many objects are exposed as though they were part of the filesystem. – Duncan Nov 03 '17 at 12:39
  • 1
    Ahhh, okay. Alias is a PS "drive" that shows up under `Get-PSDrive`, and there are options that show up under `Get-ChildItem alias:l*`, which can simply be tested via. `Test-Path alias:l*`. Knowing about `Get-ChildItem alias:` makes sense of everything. Thanks. – Andrew Nov 03 '17 at 15:37
16

I think Get-Alias is what you are looking for.

MS Documentation: http://technet.microsoft.com/en-gb/library/ee176839.aspx

Example for IF:

$ar = get-alias -name f* 
if($ar.count -lt 1){ do stuff }
Paul
  • 5,524
  • 1
  • 22
  • 39
  • Exactly what I was looking for ... what about ==> if (get-alias -name list* | Measure | ? -eq 0) { # do work } <=== would that work? – IbrarMumtaz Jan 03 '14 at 15:15
  • 5
    Don't you have a powershell prompt right there in front of you? – EBGreen Jan 03 '14 at 15:26
  • @IbrarMumtaz, your command using `Measure` looks overkill. `if(!(get-alias -name list*)) { write-output "No alias" }` – Duncan Jan 04 '14 at 09:25
  • @Duncan, just trying to learn whats possible and whats not, that's all really. – IbrarMumtaz Jan 04 '14 at 13:21
  • 1
    This approach raises an error if there are no matches and you're using `Set-StrictMode -Version 2.0`(https://technet.microsoft.com/en-us/library/hh849692(v=wps.620).aspx) . Duncan's answer is a much safer way of testing for the existance of an alias/aliases. – Kev Dec 25 '15 at 05:40
  • Why does the example match against "f*" for IF? Shouldn't it be "if*"? – crokusek Jan 09 '19 at 02:15
  • @crokusek it doesnt match to "if" in my testing, could you clarify? – Paul Jan 09 '19 at 14:07
  • Never mind, I thought "IF" was the name of some alias you were searching for. – crokusek Jan 09 '19 at 20:23
  • **Note:** Be sure to check if the command is actually an _alias_. In newer versions of powershell `Get-Command help` will show that `help` is actually a function, despite behaving like an alias to `Get-Help`. Functions can be handled with `Test-Path Function:\help`/`Remove-Item Function:\help` – PotatoFarmer Jun 03 '19 at 22:50
5

Yes, use the Get-Alias command.

Example:

Get-Alias -Name spps;

# If statement example
if (Get-Alias -Name spps) {
    # Do something here
}

To get a list of all commands that deal with aliases, use Get-Command

Get-Command -Name *alias;
  • How would you use that in an if statement? i.e can you use it with conditional logic? Sort of like if Alias does not exist, go ahead and set one up. That kind of thing. – IbrarMumtaz Jan 03 '14 at 14:54
  • 1
    The `if` statement is existential by default, so all you have to do is say: `if () { ... }`. I updated my example code :) –  Jan 03 '14 at 15:01
  • Get-Alias throws an error if the specified alias does not exist – codeulike Mar 17 '23 at 22:14
3

There is a provider just for Aliases, and an Alias: location, so you can also use Get-Childitem.

Get-Childitem alias: 
mjolinor
  • 66,130
  • 7
  • 114
  • 135
1

Another option if you are just wanting to set an alias if it does not already exist is to use the -Force parameter in Set-Alias, so you do not get an error saying the alias already exists:

Set-Alias "foo" MyFooFunction -Force

Things like if(!(Get-Alias -Name foo)) error if the alias does not exist.

Rhumborl
  • 16,349
  • 4
  • 39
  • 45
1

(tested in version 5)

Here is how I use the above (Big thanks to all!):

If ((Test-Path alias:foo) -eq $false) {New-Alias -name foo -value Get-Foo}

This is at the bottom of every script that is or will become a module. It puts an alias on the user's system without throwing an error or overwriting an existing alias if the alias already exists.

T-Heron
  • 5,385
  • 7
  • 26
  • 52
Dana
  • 71
  • 1
  • 4
1

Inspired from answers provided by Duncan and Dana, I have created the following function. i recommend adding it to the file pointed by your PowerShell's $PROFILE variable.

function New-AliasSafe {
    param(
        [Parameter(Mandatory=$true)]
        [string]
        $Name,

        [Parameter(Mandatory=$true)]
        [string]
        $Value
    )

    if (!(Test-Path alias:$Name)) {
        New-Alias -Name $Name -Value $Value -Scope Global
        Write-Verbose "Alias $Name created successfully!"
    } else {
        Write-Verbose "Another alias with $Name already exists!"
    }
}

Now you can just call this function whenever you want to import an alias.

New-AliasSafe -Name wo -Value Write-Output

If you want to know whether the alias was successfully created or not, you can call this function like this instead.

New-AliasSafe -Name wo -Value Write-Output -Verbose
Parth Shah
  • 2,060
  • 1
  • 23
  • 34
0

Just wanted to add yet another way to achieve this..

$ErrorActionPreference = 'Stop'
$ee = @() # Exception catcher
$Newalias = 'wv'
try{
New-Alias -Name $Newalias -Value Write-Verbose | Out-Null
}
catch{$ee += $_}

if (($ee -ne $null) -and ($ee.CategoryInfo.Category.ToString() -match 'ResourceExists')){Write-Warning "Alias $Newalias already exists";break}
else{Write-Verbose 'Continue on'}

Catch the exception and check if that matches the condition for the Boolean logic of existence. I've found this works well unless the exception is different than you were expecting.

4x0v7
  • 13
  • 5