b1ackjosh February 2016

Is there a !$ equivalent in powershell?

Is there a !$ equivalent in powershell? Essentially, I'd like to be able to use a command like

mv *.txt ~\Documents

And then be able to use something like

cd !$

And that should take me to the Documents folder specified in the previous command. I use it all the time in linux and it bugs me that it's not like that in powershell.

Thanks!

Edit: When using $$ I get the following error

PS C:\Users\josh.howard\Desktop\test> mv *.mp 'C:\Program Files\LANDesk\ManagementSuite\ldscan'

PS C:\Users\josh.howard\Desktop\test> cd $$
cd : Cannot find drive. A drive with the name ''C' does not exist.
At line:1 char:1
+ cd $$
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: ('C:String) [Set-Location], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

Answers


Matt February 2016

about_automatic_variables has the immediate answer to what you are looking for here.

$$

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

In practice this should have worked.

PS C:\Users\josh.howard\Desktop\test> mv *.mp 'C:\Program Files\LANDesk\ManagementSuite\ldscan'

PS C:\Users\josh.howard\Desktop\test> cd $$

However in your case there is a problem with the embedded quotes of the token.

cd : Cannot find drive. A drive with the name ''C' does not exist.

I am able to replicate this issue using PowerShell v4. Normally when you sent a quoted string to a cmdlet like Set-Location the parser will consume the quotes then send the full path to the parameter Path. Using $$ with your test case is actually sending the unescaped quoted string! That is why removing them make the process work.

cd ($$.Trim("'"))

Bill Stewart has a process to address this issue as well.

It is possible this has been addressed in v5 but I cannot confirm this exact situation.

So I tested this in windows 10 and it seems to work there, but not in version 4. So it seems to have been fixed as long as your on something newer than 4.


Bill_Stewart February 2016

Here's a sample cd function that works with $$:

function cd {
  param(
    [String] $path
  )
  Set-Location $path.Trim('"').Trim("'")
}

Post Status

Asked in February 2016
Viewed 2,672 times
Voted 6
Answered 2 times

Search




Leave an answer