PowerShell 簡單別名(Set-Alias)無法固化參數。例如想讓 tc 等價於 Test-Connection -Count 2 -ComputerName,直接別名做不到。
function Test-Conn {
param([string[]]$ComputerName)
Test-Connection -Count 2 -ComputerName $ComputerName
}
Set-Alias tc Test-Conn
使用效果:
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
function 定義一個帶參數的命令單元,param 區聲明參數列表。-Count 2),將變參($ComputerName)透傳。Set-Alias 給函數起短名,調用時體驗與原生命令一致。function Get-ServiceEx {
param(
[Parameter(ValueFromPipeline=$true)][string[]]$Name,
[switch]$Running
)
$cmd = 'Get-Service'
if ($Running) { $cmd += ' | Where-Object {$_.Status -eq "Running"}' }
if ($Name) { $cmd += " -Name $Name" }
Invoke-Expression $cmd
}
Set-Alias gse Get-ServiceEx
現在可以:
gse wuauserv # 查詢單個服務
'wuauserv','bits' | gse # 管道傳入多個名稱
gse -Running # 只看運行中的
Verb-Noun 規範(如 Test-Conn),別名用短小易記字符(tc)。$PROFILE(notepad $PROFILE),每次啟動自動載入。.ps1,函數僅做參數封裝與組合。| 現象 | 原因 | 修正 |
|---|---|---|
| 參數不生效 | 函數未聲明 param 或變量名錯誤 | 檢查 param([string[]]$Args) 拼寫,建議顯式命名而非用 $args |
| 管道傳遞失效 | 缺少 ValueFromPipeline=$true | 在 param 屬性中添加 |
| 別名衝突 | 同名別名已存在 | Get-Alias tc 查看,Remove-Alias tc 後重建 |