Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - How does a cmdlet return value?

Tags:

powershell

Please consider the following PowerShell assignment statement:

$rc = (gci -r -fi *.rar)

If there is a rar file present in the directory structure, then echo $? displays the following:

    Directory: C:\file tests

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         7/22/2012   7:09 PM    3699776 somefile.rar

Fine. Now consider this PowerShell if statement:

if (gci -r -fi *.rar)
{
    echo "Rar files found"
}
else 
{
    echo "No rar files"
}

In the if statement, the return from the gci cmdlet is treated as a boolean value. But the return from the same cmdlet produced a string output in case of the earlier assignment statement.

I know that PS is an object shell. I understand cmdlets act differently depending on context. But what I don't understand is how this is accomplished, and what mechanisms are used.

Specifically: What is the magic used by the if statement that allows the return from gci to be treated as a boolean? If I wanted to use that mechanism elsewhere (outside of an if statement), what would I have to do? Is there some sort of a "cast to boolean" operator? E.g.

$rc = (Cast following to boolean)(gci -r -fi *.rar)
like image 760
Sabuncu Avatar asked Oct 11 '25 15:10

Sabuncu


1 Answers

This table gives you the answer.

True                                         False
~~~~                                         ~~~~~
$TRUE                                        $FALSE
Any string of length > 0                     Empty string
Any number ≠ 0                               Any number = 0
Array of length > 1                          Array of length 0
Array of length 1 whose element is true      Array of length 1 whose element is false
A reference to any object  <<<<<             $NULL

Idea behind this is to use similar checks to verify if an object is initialized properly.

like image 172
Klark Avatar answered Oct 15 '25 09:10

Klark