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 ?

Clijsters
  • 4,031
  • 1
  • 27
  • 37
Raja G
  • 5,973
  • 14
  • 49
  • 82
  • 1
    The PowerShell equivalent of that command would be `mkdir 20171206 | cd`. – Ansgar Wiechers Dec 06 '17 at 12:36
  • You didn't really explain what bash's `$_` does. I would start by looking at [`Get-Help about_Automatic_Variables`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-5.1). – Bacon Bits Dec 06 '17 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. – Clijsters Dec 06 '17 at 12:41
  • So, we can achieve it some way. thats all I need. have a great day team. – Raja G Dec 06 '17 at 12:47

1 Answers1

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
Bacon Bits
  • 30,782
  • 5
  • 59
  • 66