在Powershell中設置別名的確方便快捷,但是在設置別名的過程中并設置參數(shù)的相關信息。盡管別名會自動識別參數(shù),但是如何把經(jīng)常使用的參數(shù)默認設定在別名里面呢?例如Test-Connection -Count 2 -ComputerName,讓-”-Count 2″ 固化在別名中。
這時簡單的別名無法完成上述需求,可以通過函數(shù)來完成它,并且一旦把函數(shù)拉過來,定義別名會變得更加靈活。
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
有了函數(shù)牽線,別名可以完成更高級更強大的功能,其中$args為參數(shù)的占位符,經(jīng)測試,發(fā)現(xiàn)這個占位符必須以$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 執(zhí)行文件和腳本
- Windows Powershell 定義變量
- Windows Powershell 自動化變量
- Windows Powershell 環(huán)境變量
- Windows Powershell 變量的作用域