Powershell Remove-Item not working from a function

Viewed 732

I needed to replace the Alias 'cd' with my function named 'cd'.

I tried to remove the alias from a function, but it didn't work. The following was a simple testing script,

function remove_alias {
    get-command cd
    Remove-Item -Path Alias:cd
    get-command cd
}    
remove_alias

I ran it from Windows 10 and native Powershell version 5.1.18362.752. The output was below. The alias didn't change

PS> . .\test_remove_alias.ps1

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cd -> Set-Location
Alias           cd -> Set-Location

If moved the Remove-Item out of the function. It worked.

get-command cd
Remove-Item -Path Alias:cd
get-command cd

The output was below and the alias was replaced by my function.

PS> . .\test_remove_alias2.ps1

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cd -> Set-Location
Function        cd

I'd like to remove the alias from a function as function is better way to manage code.

This seems to be a generic question but I haven't found any answer from internet.

1 Answers

I think this is just a problem with your changes being scoped only to the inside of your function. To fix this, you can call the function within the current scope by prefixing with . , see PowerShell - execute script block in specific scope

function remove_alias {
    get-command cd
    Remove-Item -Path Alias:cd
    get-command cd
}

. remove_alias

Result:

CommandType     Name                                               Version    Source                                                                                                                                                 
-----------     ----                                               -------    ------                                                                                                                                                 
Alias           cd -> Set-Location                                                                                                                                                                                                   
get-command : The term 'cd' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:4 char:5
+     get-command cd
+     ~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (cd:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Also works within a ps1 file, also called with . :

running in a ps1 file

Related