问题描述
我需要用名为“ cd”的函数替换别名“ cd”。
我试图从函数中删除别名,但是没有用。以下是一个简单的测试脚本,
function remove_alias {
get-command cd
Remove-Item -Path Alias:cd
get-command cd
}
remove_alias
我从Windows 10和本机Powershell版本5.1.18362.752运行了它。输出如下。别名没有改变
PS> . .\test_remove_alias.ps1
CommandType Name Version Source
----------- ---- ------- ------
Alias cd -> Set-Location
Alias cd -> Set-Location
如果将Remove-Item移出了功能。有效。
get-command cd
Remove-Item -Path Alias:cd
get-command cd
PS> . .\test_remove_alias2.ps1
CommandType Name Version Source
----------- ---- ------- ------
Alias cd -> Set-Location
Function cd
这似乎是一个普遍的问题,但我没有从互联网上找到任何答案。
解决方法
我认为这只是一个问题,您所做的更改仅作用于函数内部。要解决此问题,您可以在当前范围内通过以dirty
为前缀来调用该函数,请参见PowerShell - execute script block in specific scope
.
结果:
function remove_alias {
get-command cd
Remove-Item -Path Alias:cd
get-command cd
}
. remove_alias
还可以在ps1文件(也称为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
)中工作: