在Powershell中設置別名的確方便快捷,但是在設置別名的過程中并設置參數的相關信息。盡管別名會自動識別參數,但是如何把經常使用的參數默認設定在別名里面呢?例如Test-Connection -Count 2 -ComputerName,讓-”-Count 2″ 固化在別名中。
這時簡單的別名無法完成上述需求,可以通過函數來完成它,并且一旦把函數拉過來,定義別名會變得更加靈活。
PS C:\PS> function test-conn { Test-Connection -Count 2 -ComputerName $args}
PS C:\PS> Set-Alias tc test-conn
PS C:\PS> tc localhost
Source Destination IPV4Address IPV6Address Bytes Time(ms)
------ ----------- ----------- ----------- ----- --------
test-me-01 localhost 127.0.0.1 ::1 32 0
test-me-01 localhost 127.0.0.1 ::1 32 0
有了函數牽線,別名可以完成更高級更強大的功能,其中$args為參數的占位符,經測試,發現這個占位符必須以$args命名,否則不能識別,會拋出異常:
Cannot validate argument on parameter ‘ComputerName'. The argument is null or empty. Supply an arg
nt that is not null or empty and then try the command again.
您可能感興趣的文章:- Windows Powershell 執行文件和腳本
- Windows Powershell 定義變量
- Windows Powershell 自動化變量
- Windows Powershell 環境變量
- Windows Powershell 變量的作用域