別名混亂 - 是什麼將“vm”映射到“Get-VM”?

別名混亂 - 是什麼將“vm”映射到“Get-VM”?

打算從此啟動vim

PS C:\temp> get-command vim | select name,source

Name    Source
----    ------
vim.bat C:\Users\noam\AppData\Local\Microsoft\WindowsApps\vim.bat

我不小心進入了vm而不是,隨之vim而來的是很多令人頭痛的事情:

C:\temp>pwsh -noprofile
PowerShell 7.4.1
PS C:\temp> vm
Get-VM: 29-Mar-24 16:28:14      Get-VM          You are not currently connected to any servers. Please connect first using a Connect cmdlet.
PS C:\temp> get-command vm
Get-Command: The term 'vm' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
PS C:\temp> get-alias vm
Get-Alias: This command cannot find a matching alias because an alias with the name 'vm' does not exist.
PS C:\temp> cmd /c where vm
INFO: Could not find files for the given pattern(s).

如何找到並刪除看似從 VMware PowerCLI映射vm到的配置?Get-VM

PS C:\temp> get-command get-vm | select Name,Source

Name   Source
----   ------
Get-VM VMware.VimAutomation.Core

我一定是錯過了一些愚蠢的事情。我以為上面的呼叫where.exe應該發現了與我的路徑相關的任何內容。無論如何,設定後行為不會改變$env:PATH = $null

作為一個拼湊,我可以明確地重新定義vmviaSet-Alias到一些不存在的指令。但我想了解為什麼在執行時看不到類似下面的內容vm。我忽略了什麼?

PS C:\temp> doesnotexist
doesnotexist: The term 'doesnotexist' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

無論是否VMware.VimAutomation.Core明確導入模組,上述結果都可以重現。

答案1

這不是一個“別名問題”,它是 PowerShell 的“動詞優先”命令命名方法的一部分。

Get-當未指定動詞時,PowerShell 會自動採用cmdlet 上的動詞。

childitem您可以透過簡單地編寫一些命令(例如 等)來嘗試locationGet-ChildItemGet-Location

這也解釋了您嘗試找出此行為的不同 cmdlet 的行為:

  • Get-Command vm- 由於 vm 不是命令,因此未找到它。
  • Get-Alias vm- 由於它也不是別名,因此您也無法在這裡找到它。

此行為不適用於使用者定義的函數或控制台應用程序,這就是為什麼您可以建立呼叫的函數DoStuff,但 PowerShell 不會自動執行此操作Get-DoStuff

您無法變更此行為,但vm如果您確實想這樣做,則可以建立執行其他操作的函數。

相關內容