I can't work this out. I am storing 0's and 1's in a CSV file, in the column named "Test". Using import-csv
to read them back into Powershell, in an array, and in a for loop have used:
[System.Convert]::ToBoolean($Array[$i].Test)
Produces error "Exception calling "ToBoolean" with "1" argument(s): "String was not recognized as a valid boolean"
[boolean]($Array[$i].Test)
which at least doesn't error out, but does make both 0 and 1 return as true.
Here is tests on $Array[0].Test
:
Value (delimited with "'s):
"0"
GetType():
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
EDIT:
Did more tests.
Created a PSObject to be equivalent to the $String.Test
:
$String = [pscustomobject]@{
Test = 0
}
Running gettype()
against it I get:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
Then putting it into CSV:
$Array | export-csv c:\temp\test.csv -notypeinformation -noclobber -erroraction silentlycontinue
And back into an array:
$Array2 = import-csv C:\temp\test.csv
Running gettype()
against $Array2[0].test
:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
I notice that Base Type is now System.Object
, not 'System.ValueType', though not sure if this has any bearing on the problem.
But still, why is a 0 in string form not being converted to $false?
On re-read of the casting rules on MS' website I see the problem. Int will convert 0 to $false, 1 to $true. But string is evaluated on it's length?! (Zero length, $false; Any other length $true). Only char (for those that need a reminder, a single character variable class) of 0/1 will convert to their int
relative boolean values.