Using multiple statements in the selection criteria for Where-Object

Christopher Jack 1,611 Reputation points
2021-03-26T14:34:48.29+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

1 answer

Sort by: Most helpful
  1. Michael Taylor 48,206 Reputation points
    2021-03-26T16:13:46.413+00:00

    $td is an array of objects, not ints. You can store whatever you want in it.

    $td = @()
    $td += 10
    $td += "Hello"
    $td += 45.67
    

    If you want to store only ints then type it explicitly.

    [int[]] $td = @()
    $td += 10
    $td += "Hello" # Error
    

    But later in your code it looks like $td should be an array of strings since you're converting a date to a formatted string.

    Moving on to your next issue, you're using a comma in the for and you need a semicolon. Commas are used to separate array elements so PS is seeing an array.

    [string[]] $td = @()
    $test = 4
    for ($x = 1; $x -le $test; $x++) {
       $td += (Get-Date).AddDays(-$x).ToString('dd/MM/yyyy')
    }
    
    0 comments No comments