JohnLBevan
JohnLBevan

Reputation: 24410

PowerShell Variables `${$}`, `${^}` and `$?`

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.

$? 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

Answers (3)

Mark Wragg
Mark Wragg

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

JohnLBevan
JohnLBevan

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

restless1987
restless1987

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

Related Questions