有没有办法引用先前输入的命令的倒数第二个单词(例如$^表示第一个单词,$$表示最后一个单词)
在PowerShell中输入命令时,可以参考我与最近输入的命令的第一个和最后一个字的数值$^和$$。我想知道是否有一个快捷方式来引用倒数第二个、倒数第 n 个或第 n 个单词。
回答
没有直接等同于您提到的自动变量,但您可以结合Get-HistoryPowerShell 的语言解析器 ( System.Management.Automation.Language.Parser) 来实现您的意图:
function Get-PrevCmdLineTokens {
# Get the previous command line's text.
$prevCmdLine = (Get-History)[-1].CommandLine
# Use the language parser to break it into syntactic elements.
$tokens = $null
$null = [System.Management.Automation.Language.Parser]::ParseInput(
$prevCmdLine,
[ref] $tokens,
[ref] $null
)
# Get and output an array of the text representations of the syntactic elements,
# (excluding the final `EndOfInput` element).
$tokens[0..($tokens.Count - 2)].Text
}
例子:
PS> $null = Write-Output Honey "I'm $HOME"
PS> Get-PrevCmdLineTokens
以上产生:
$null
=
Write-Output
Honey
"I'm $HOME"
笔记:
-
与
$^and 一样$$,组成命令的标记是unexpanded,这意味着它们被表示为类型而不是它们的内插值。 -
然而,不同于与
$^和$$,任何句法引用被保持(例如,"I'm $HOME"而不是I'm $HOME)。- 虽然您可以在上面的函数中使用
.Value代替.Text来去除句法引用,但您会错过诸如$nulland 之类的标记=。
- 虽然您可以在上面的函数中使用
THE END
二维码