在 PoserShell 上建立指令別名 Alias

有許多指令很長,每次要輸入很煩瑣,我們可以建立指令別名,這樣以後輸入別名就可以了,不用輸入完整的指令。

建立指令別名

在 PowerShell 中可以使用 test-netconnection 指令來測試 port 連接是否可以正常連接,使用範例如下:
    
test-netconnection 192.168.0.10 -p 80
    

但是 test-netconnection 這個指令太長了不方便輸入,我們可以使用下面的指令自訂別名,這裡示範定義成 testport :
    
New-Alias -Name testport -Value test-netconnection
    

這樣以後就可以使用 testport 來取代 test-netconnection 方便輸入:
    
testport 192.168.0.10 -p 80
    

儲存別名

不過上面的設定別名只在當前的指令視窗中有效,如果想要在其他指令視窗中也可以執行,那就要寫入到設定檔中。

編輯設定檔:
    
notepad $Profile
    

如果出現「找不到指定的路徑」,則代表未曾建立過 PowerShell 設定檔,可以使用下面的指令建立設定檔,再次編輯設定檔就可以正常開啟了
    
New-Item -Path $profile -ItemType "file" -Force
    

然後再最後面加入設定別名的指令即可:
    
New-Alias -Name testport -Value test-netconnection
    

包含參數的指令別名

沒有辦法直接建立包含參數的指令別名,不過有替代的方式,就是建立 function,例如輸入 testport-server1 就想要查看 192.168.0.10 的 80 port 是否可以正常連接,就可以使用下面的指令達成:
    
function testport-server1 {test-netconnection 192.168.0.10 -p 80}
    

如果想要永久有效,就使用上面的步驟加入至設定檔即可。

常用別名指令

取得所有別名
    
Get-Alias
    

查看 t 開頭的別名:
    
Get-Alias -Name t*
    

範例輸出:
    
Get-Alias -Name t*

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           tee -> Tee-Object
Alias           testport -> Test-NetConnection
Alias           TNC -> Test-NetConnection                          1.0.0.0    NetTCPIP
Alias           trcm -> Trace-Command
Alias           type -> Get-Content
    



參考資料:
Microsoft.Learn - about_Aliases

留言