Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the arguments of the last invoked command in powershell?

Tags:

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. Get-History -count 1 returns the last full command including the command and the 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?

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.

like image 251
esac Avatar asked Nov 12 '10 18:11

esac


1 Answers

For the last argument (not all!) in the interactive hosts like Console and ISE it is the automatic variable $$.

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).

like image 114
Roman Kuzmin Avatar answered Oct 06 '22 22:10

Roman Kuzmin