Reputation: 24410
Does anyone know what the following variables are used for in PowerShell:
${$}
${^}
$?
From what I can tell ${^}
and ${$}
both relate to the last executed command line (if you're running these as a script via ISE they relate to the command executed before the script was run, rather than the prior line in the same script). The difference seems to be that ${^} returns the command up to the first whitespace character, whilst ${$} returns everything after the last whitespace character. i.e.
$chevron = $lastCommand -replace '^([^\s]*).*$', '$1'
$dollar = $lastCommand -replace '^.*?([^\s]*)$', '$1'
$?
meanwhile seems to always return true
.
I spotted these variables when they showed up in the ISE's auto-complete feature.
I'm sure this is documented, but I've struggled to find the right search terms to find the answers / anything but noise.
Upvotes: 1
Views: 122
Reputation: 23355
$$
Contains the last token in the last line received by the current session.
$?
Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.
$^
Contains the first token in the last line received by the session.
Upvotes: 1
Reputation: 24410
Googling by character name instead of the character itself worked!
http://www.neolisk.com/techblog/powershell-specialcharactersandtokens
${^}
can also be written $^
. This gives the first token of the last command. This is similar to what I'd said in the question, only a token may include whitespace; rather things are split based on the parsed code. To illustrate: 'number 1', 'number 2' | Write-Host
would return number 1
instead of 'number
.
${$}
/ $$
likewise returns the last token. i.e. after running write-host -ForegroundColor green -Object 'hello, is it me you''re looking for?'
, $$
gives hello, is it me you're looking for?
.
$?
returns true if the previous command was successful. To demonstrate where it's false, running 1/0
then $?
will give a false result.
Upvotes: 3
Reputation: 1598
For $?:
$? Contains the execution status of the last operation. Equivalent to %errorlevel% in the CMD shell. See also $LastExitCode below. It contains TRUE if the last operation succeeded and FALSE if it failed. ReadOnly, AllScope. (https://ss64.com/ps/syntax-automatic-variables.html)
The rest is documented there too.
Upvotes: 1