SoFunction
Updated on 2025-03-10

Windows Powershell extends aliases through functions

Setting an alias in Powershell is indeed convenient and fast, but during the process of setting an alias and setting relevant information about parameters. Although aliases will automatically recognize parameters, how to set the frequently used parameters in the aliases by default? For example, Test-Connection -Count 2 -ComputerName, and let-"-Count 2" solidify in the alias.

At this time, simple aliases cannot complete the above requirements, they can be completed through functions, and once the function is pulled over, defining aliases will become more flexible.

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

With function matching, alias can complete more advanced and powerful functions, where $args is the placeholder for the parameter. After testing, it was found that this placeholder must be named after $args, otherwise it will not be recognized and an exception will be thrown:
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.