Reputation: 6854
In PowerShell, help about_Automatic_Variables
gives definitions that are plain enough, but don't provide an example of how they might be useful:
$$
Contains the last token in the last line received by the session.
$^
Contains the first token in the last line received by the session.
Why are these first/last tokens useful enough to have justified a language feature like this?
Does it have something to do with TAB completion?
Upvotes: 1
Views: 104
Reputation: 47792
These come from their cousins in Unix shells (see !!
in this answer). They are not useful in scripts, but they are useful [Citation Needed] when using PowerShell as a shell.
For example:
C:\Users\Briantist> Get-Service Workstation
C:\Users\Briantist> Start-Service $$
They save you from having to type the last token over again. A long path or otherwise complicated token can be a pain to type.
Similarly with $^
, it allows you to reuse the first token:
C:\windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -command '[Environment]::Is64BitProcess'
# Run a 32-bit version of powershell and test that it's not 64 bit
$^ -command '<# an actual command you wanted to run in 32 bit #>'
My guess is that these seemed more useful when the language was first being designed, but I don't personally think they ended up being that useful.
Because piping from one command to another is often more idiomatic in PowerShell (and in some ways and situations used more extensively than in Unix), the first example with $$
, would probably be more like this:
Get-Service Workstation
(sees output, uses ↑ to get that previous command on the line), then:
Get-Service Workstation | Start-Service
Upvotes: 2