[英]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 - 在特定范圍內執行腳本塊
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 文件,也稱為.
:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.