PowerShell从函数中删除项目无法正常工作。

5
我需要将别名“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

我想从一个函数中移除别名,因为函数是更好管理代码的方式。
这似乎是一个通用的问题,但我在互联网上没有找到任何答案。
1个回答

2

我认为这只是因为您的更改仅限于函数内部的范围问题。要解决此问题,您可以通过在当前范围前缀中调用该函数来解决问题,如.所示,请参见PowerShell - execute script block in specific scope

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

. remove_alias

结果:

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

这个命令还可以在ps1文件中使用,也可以通过调用

running in a ps1 file


谢谢Jacob。这个可行!!!我也看了你的链接。“调用运算符(&)总是使用新作用域。相反,使用点源(.)运算符:”非常有帮助。 - oldpride
1
@oldpride 很高兴听到这个消息!如果这是一个合适的答案,您是否介意通过点击上下投票按钮下面的复选标记来接受它? - Jacob Colvin
肯定没问题。我还在寻找一个关闭此案例的按钮。我不知道复选标记就是按钮。再次感谢。 - oldpride
1
remove-item 命令不仅可以删除别名,还可以删除函数。 - Timo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接