question

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

Using multiple statements in the selection criteria for Where-Object

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

cooldadtx avatar image
0 Votes"
cooldadtx answered

$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')
}

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.