bashshellpowershellshautomatic-variable

Powershell equivalent to $_ in bash


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 ?


Solution

  • 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