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)
$(gci -r -fi *.rar) -eq $null
$(...)
surrounding thegci -r -fi *.rar
do? I have tried it without the dollar sign, and it still works. I.e.(gci -r -fi *.rar) -eq $null