0

In bash, to get argument from last command we call $_. I have searched but couldn't find what is equivalent to bash's $_ in PowerShell ? Example:

$ mkdir 20171206
$ cd $_

Now bash current working directory would be 20171206 and I am trying to achieve same via PowerShell.

Is it possible ?

4
  • 1
    The PowerShell equivalent of that command would be mkdir 20171206 | cd. Commented Dec 6, 2017 at 12:36
  • You didn't really explain what bash's $_ does. I would start by looking at Get-Help about_Automatic_Variables. Commented Dec 6, 2017 at 12:36
  • 1
    Agree with @BaconBits, but Ansgars comment wasn't intended to answer the question and showed how to do it the PowerShell way. IMHO it's important tu use one language's features instead of trying to rebuild another languages functionality. Commented Dec 6, 2017 at 12:41
  • So, we can achieve it some way. thats all I need. have a great day team. Commented Dec 6, 2017 at 12:47

1 Answer 1

1

Apparently, $_ in bash means "last argument of previous command".

The closest approximation of that is $$, which is defined as:

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

However, I don't know if that means PowerShell's $$ behaves like bash's $_ or if it behaves like bash's !$. I think it's closer to !$, but I'm on my Chromebook at the moment and can't confirm.

Edit: It's like !$:

PS C:\> Get-Location > a.txt
PS C:\> $$
a.txt

So there's no direct equivalent to bash's $_.

Keep in mind, though, that PowerShell strongly favors objects and pipes, so retaining the bash convention of thinking about everything in terms of plain text and space-delimited tokens won't serve you as well. The best way to do this in PowerShell is:

mkdir 20171206 | cd

Or, if you're not using any of the default PowerShell aliases and functions (I'm not sure what gets retained on Linux PowerShell, for example):

New-Item 20171206 -ItemType Directory | Set-Location
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.