簡體   English   中英

獲取powershell中最后一個被調用命令的參數?

[英]Getting the arguments of the last invoked command in powershell?

我希望能夠獲得上一個命令的參數部分。 $^似乎只返回命令而不是args。 Get-History -count 1返回最后一個完整命令,包括命令和args。 我可以。更換第一個實例,但我不確定它是否正確。

情景是有時我想做這樣的事情。 我們假設$ *是最后一個命令的參數:

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

任何想法如何正確獲得最后的args?

更新:完成了我的方法。

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

如果有人有任何改善這個想法的想法,請告訴我。

對於像Console和ISE這樣的交互式主機中的最后一個參數(不是全部!),它是自動變量$$

救命

man about_Automatic_Variables

得到

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

其他主機可能會也可能不會實現此功能(以及$^變量)。

沒有解析歷史項目本身就沒有簡單的方法可以以這種方式獲得最后的args,這不是一件小事。 原因是,在將splatting,pipelines,嵌套子表達式,命名和未命名的參數/參數帶入等式之后,“最后的參數”可能不是您認為的那樣。 在powershell v2中,有一個解析器可用於標記命令和表達式,但我不確定你是否想要去那條路。

ps> $psparser::Tokenize("dir foo", [ref]$null) | ? {
    $_.type -eq "commandargument" } | select -last 1 -expand content
foo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM