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

Christopher Jack 1,611 Reputation points
2021-03-26T14:36:05.693+00:00

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
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,364 questions
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 31,571 Reputation points
    2021-03-26T15:01:58.01+00:00

    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
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful