question

ChristopherJack-1763 avatar image
0 Votes"
ChristopherJack-1763 asked MotoX80 answered

Strange typecasting happening in loop - Powershell "System.Object[]" to type "System.Int32"."

Trying to do a simple loop to populate an array

 [array]$td= @()
 [int]$test = 4
 [int]$x = 0
 for($x=1,$x -le $test, $x++)
 {
 $Temp = (Get-date).AddDays(-$x)
 $td += Get-Date $Temp -Format dd/MM/yyyy
 }
 $td

Error message is due to type casting.. yet I am setting what I want them to be and also seem to be getting a spurious 0?

Error is

Line |

7 | for($x=1,$x -le $test, $x++)
| ~~~~~~~~~~~~~~~~~~~~~~~
| Could not compare "1" to "4 0". Error: "Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32"."


windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

MotoX80 avatar image
1 Vote"
MotoX80 answered

You need to use semi-colons, not commas.

  [array]$td= @()
  [int]$test = 4
  [int]$x = 0
  for($x=1;$x -le $test; $x++)
  {
     "X={0}" -f $x 
     $Temp = (Get-date).AddDays(-$x)
     $td += Get-Date $Temp -Format dd/MM/yyyy
  }
  $td
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.