Powershell的abbr
#--- abbr ---
# 缩写定义:左边是简写,右边是展开后的完整命令
$global:abbrs = @{
'g' = 'git'
'gcm' = 'git commit -m'
'gst' = 'git status'
'glg' = 'git log'
'gco' = 'git checkout'
'gad' = 'git add'
'll' = 'Get-ChildItem -Force'
'k' = 'kubectl'
}
# 展开逻辑:把光标前的词替换成完整命令
$expandAbbr = {
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
if ($cursor -gt 0) {
$before = $line.Substring(0, $cursor)
if ($before -match '(?<Word>\S+)$') {
$word = $Matches['Word']
if ($abbrs.ContainsKey($word)) {
[Microsoft.PowerShell.PSConsoleReadLine]::Replace(
$cursor - $word.Length,
$word.Length,
$abbrs[$word]
)
}
}
}
}
# 空格:先展开,再插入空格
Set-PSReadLineKeyHandler -Key Spacebar -ScriptBlock {
& $expandAbbr
[Microsoft.PowerShell.PSConsoleReadLine]::Insert(' ')
}.GetNewClosure()
# 回车:先展开,再执行
Set-PSReadLineKeyHandler -Key Enter -ScriptBlock {
& $expandAbbr
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}.GetNewClosure()
🕐💭 短文