代码之家  ›  专栏  ›  技术社区  ›  esac

正在获取powershell中最后调用的命令的参数?

  •  9
  • esac  · 技术社区  · 15 年前

    我希望能够得到前一个命令的参数部分。 $^ 似乎只返回命令而不是参数。 Get-History -count 1 返回最后一个完整命令,包括命令和参数。我可以。替换第一个实例,但我不确定它是否正确。

    情况是,有时我想做这样的事情。假设$*是最后一个命令的参数:

    dir \\share\files\myfile.exe
    copy $* c:\windows\system32
    

    有什么办法可以正确地得到最后一个参数吗?

    更新:完成了我的方法。

    function Get-LastArgs
    {
        $lastHistory = (Get-History -count 1)
        $lastCommand = $lastHistory.CommandLine   
        $errors = [System.Management.Automation.PSParseError[]] @()
    
        [System.Management.Automation.PsParser]::Tokenize($lastCommand, [ref] $errors) | ? {$_.type -eq "commandargument"} | select -last 1 -expand content    
     }
    

    现在我可以做:

    dir \\share\files\myfile.exe
    copy (Get-LastArgs) c:\windows\system32
    

    为了减少打字,我做了

    set-alias $* Get-LastArgs
    

    所以现在我还得做

    copy ($*) c:\windows\system32
    

    如果有人有任何改进的想法,请告诉我。

    2 回复  |  直到 15 年前
        1
  •  2
  •   x0n    15 年前

    如果不解析历史项本身,就无法以这种方式获取最后一个参数,这不是一件小事。原因是,在将splatting、管道、嵌套子表达式、命名和未命名的参数/参数放入equasion之后,“最后一个参数”可能不是您认为的那样。在powershell v2中,有一个解析器可用于标记命令和表达式,但我不确定您是否要走这条路。

    ps> $psparser::Tokenize("dir foo", [ref]$null) | ? {
        $_.type -eq "commandargument" } | select -last 1 -expand content
    foo
    
        2
  •  14
  •   Roman Kuzmin    15 年前

    最后一个参数(不是全部!)在像Console和ISE这样的交互式主机中,它是自动变量 $$ .

    帮助

    man about_Automatic_Variables
    

    得到

    $$
    Contains the last token in the last line received by the session.
    

    其他主机可能实现或不实现此功能(以及 $^ 变量)。

    推荐文章