Powershell Remove-Item 不适用于函数
Powershell Remove-Item not working from a function
我需要用名为 '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
我想从函数中删除别名,因为函数是管理代码的更好方式。
这似乎是一个普遍的问题,但我还没有从互联网上找到任何答案。
我认为这只是您的更改仅限于函数内部的问题。要解决此问题,您可以通过在当前范围内添加前缀 .
来调用该函数,请参阅 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 文件中使用,也可以用 .
:
调用
我需要用名为 '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
我想从函数中删除别名,因为函数是管理代码的更好方式。
这似乎是一个普遍的问题,但我还没有从互联网上找到任何答案。
我认为这只是您的更改仅限于函数内部的问题。要解决此问题,您可以通过在当前范围内添加前缀 .
来调用该函数,请参阅 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 文件中使用,也可以用 .
: