Home > Software engineering >  Can these variables be explained? What is a practical application?
Can these variables be explained? What is a practical application?

Time:09-18

I was looking through PSDrives and the variables listed there and discovered a few and I am not 100% sure what they are doing or what their practical application is.

I run: echo "test"

It returns test

Easy enough.

From here I run: $^ and it returns the last command I ran echo

When I run $$ it returns the output of the last command I ran test

Is that what they are supposed to do or is that just also what is happening here? What is the practical application?

Also.

Running $? always returns True

and running !$? always returns False

What exactly would be the purpose of using these in that context?

if(!$?){do something}

if what is false? I'm confused.

EDIT: $^ and $$ return the first and last token. So I understand that, but still don't see a practical application

CodePudding user response:

All variables you reference are so-called automatic variables in PowerShell, i.e. built in ones, as documented in the conceptual about_Automatic_Variables help topic.

  • $^ and $$, rarely used in practice, are only useful in interactive use: they, refer to the first and last token, respectively, of the previously submitted command line.

    • As such, you can use these variables to avoid having to re-type these tokens on the next command line.
    • Note that in order to re-execute the token reported in $^, you have to prefix it with &, the call operator.
  • $? is an abstract success indicator that reflects whether the most recently executed statement reported an error condition (in which case $? is $false) or not (in which case it is $true).

    • With respect to PowerShell commands, an error condition is defined as that command either reporting at least one non-terminating error or that command aborting with a statement-terminating error.

    • With respect to .NET method calls, an error condition means that an exception occurred, which surfaces as a statement-terminating error in PowerShell.

    • With respect to calls to external programs, an error condition means that such a program reports a non-zero exit code, as reflected in the automatic $LASTEXITCODE variable.

      • Caveat: In Windows PowerShell and in PowerShell (Core) up to 7.1.x, a 2> redirection can falsely indicate $false, even if the process exit code is 0, namely if the external program happens to produce stderr output - see this answer for more information.
  • Related