I have two question, acually:
Next code snippet could help out on understanding:
$arraylist = New-Object 'system.collections.arraylist'
$arraylist.Add(111) | Out-Null
$arraylist.Add([string]222) | Out-Null
$arraylist.Add('"' + 3 + '"') | Out-Null
for($i=0; $i -lt $arraylist.Count; $i++ ){
write-host $i, $arraylist[$i], $arraylist[$i].GetType()
}
write-host ''
$csv = $arraylist -join ','
$csv
Output:
0 111 System.Int32
1 222 System.String
2 "3" System.String
111,222,"3"
Additional view of (un)importance of "
double quotes in a string type shows next +
operation (sum of integers but concatenation of strings):
write-host $i, $arraylist[$i], $arraylist[$i].GetType().Name, ($arraylist[$i] + 55)
gives next output:
0 111 Int32 166
1 222 String 22255
2 "3" String "3"55
111,222,"3"
However, "
double quotes have another important and meaningful role in .csv
file when imported e.g. to Excel sheet.
I don't if this is correct. Usually, they have powershell2. Just give this a little try.
$a = @()
$strArrayNum=""
for($i=0; $i -lt $arraylist.length; $i++ ){
$strArrayNum += $element
$strArrayNum = $i+1 -eq $arraylist.length ? "" : ","
}
$a = $strArrayNum.Split(",")
In your question, you've commented out the following snippet:
($arraylist-join -',')
because it returns the error Cannot convert value "," to type "System.Int32"...
The reason for this is the dash -
in front of ','
.
In PowerShell, only operators and parameters are prefixed with a dash, and since ','
is neither (it's an argument to an operator), the PowerShell parser gets super confused and tries to treat -','
as a value expression that would result in a negative number.
Just void the dash and you'll be fine:
$arraylist -join ','
Finally, you can easily cast an array of integers to an array of strings with the unchecked cast operator -as
(PowerShell 3.0 and newer):
$StringArray = 1,2,3,4,5 -as [string[]]
or with an explicit cast (PowerShell 2.0-compatible):
$StringArray = [string[]]@(1,2,3,4,5)
This worked for me:
[String]::Join(",", $arraylist.ToArray())
I got 1,2
.
And then the second part:
foreach($number in $arraylist) { $number.ToString() }