简体   繁体   English

获取powershell中最后一个被调用命令的参数?

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

I want to be able to get the argument portion of the previous command. 我希望能够获得上一个命令的参数部分。 $^ seems to return just the command and not the args. $^似乎只返回命令而不是args。 Get-History -count 1 returns the last full command including the command and the args. Get-History -count 1返回最后一个完整命令,包括命令和args。 I could just .Replace the first instance, but I am not sure if it is correct. 我可以。更换第一个实例,但我不确定它是否正确。

Scenario is that sometimes I want to do something like this. 情景是有时我想做这样的事情。 Let's assume that $* are the args to the last command: 我们假设$ *是最后一个命令的参数:

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

Any ideas how to get the last args correctly? 任何想法如何正确获得最后的args?

UPDATE: finished my method for doing this. 更新:完成了我的方法。

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    
 }

Now I can just do: 现在我可以这样做:

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

To reduce typing, I did 为了减少打字,我做到了

set-alias $* Get-LastArgs

so now I still have to do 所以现在我还是要做

copy ($*) c:\windows\system32

if anybody has any ideas for making this better please let me know. 如果有人有任何改善这个想法的想法,请告诉我。

For the last argument (not all!) in the interactive hosts like Console and ISE it is the automatic variable $$ . 对于像Console和ISE这样的交互式主机中的最后一个参数(不是全部!),它是自动变量$$

Help 救命

man about_Automatic_Variables

gets 得到

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

Other hosts may or may not implement this feature (as well as the $^ variable). 其他主机可能会也可能不会实现此功能(以及$^变量)。

There is no easy way to get the last args in this fashion without parsing the history item itself, and this is no trivial matter. 没有解析历史项目本身就没有简单的方法可以以这种方式获得最后的args,这不是一件小事。 The reason is that the "last arguments" may not be what you think they are after you take splatting, pipelines, nested subexpressions, named and unnammed arguments/parameters into the equasion. 原因是,在将splatting,pipelines,嵌套子表达式,命名和未命名的参数/参数带入等式之后,“最后的参数”可能不是您认为的那样。 In powershell v2 there is a parser available for tokenizing commands and expressions, but I'm not sure you want to go that route. 在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