如何解决Powershell Remove-Item无法通过功能运行
我需要用名为“ 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
)中工作:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。