powershell - 有没有办法引用先前输入的命令的倒数第二个单词(例如 $^ 代表第一个单词, $$ 代表最后一个单词)

标签 powershell command-line command-line-interface

在PowerShell中,输入命令时,我可以使用$^$$引用最近输入的命令的第一个和最后一个单词的值。我想知道是否有快捷方式可以引用倒数第二个、倒数第 n 个或第 n 个单词。

最佳答案

没有与 automatic variables 直接等效的东西你提到,但你可以结合 Get-History使用 PowerShell 的语言解析器 ( 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"

注意:

  • $^$$ 一样,组成命令的标记是未扩展的,这意味着它们被表示按输入而不是插值值。

  • 但是,$^$$ 不同,任何语法引用都会被保留(例如,“I'm $HOME” 而不是 I'm $HOME)。

    • 虽然您可以在上面的函数中使用 .Value 而不是 .Text 来去除语法引用,但您会错过诸如 之类的标记>$null=

关于powershell - 有没有办法引用先前输入的命令的倒数第二个单词(例如 $^ 代表第一个单词, $$ 代表最后一个单词),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68567999/

相关文章:

ruby - 如何使用 thor -T 列出 method_options?

command-line - 如何显示共同点(反向差异)?

node.js - 如何用yarn测试cli(全局链接)?

java - 以编程方式在 Stardog 中添加自定义规则

pointers - CLI/C++:void* 到 System::Object

javac 响应 "not a file"但文件存在

powershell - Windows Powershell 中 runas/netonly 的等价物是什么?

powershell - 无法断开连接到 office365 的 powershell session

windows - DSC Pull 服务器无法注册 Windows 10 (1709) 客户端

Windows批处理脚本删除文件夹中除一个以外的所有内容