Reputation: 2448
Me and PowerShell arrays are having some difficulties today and I'm hoping someone can lend me a hand.
I'm looking to run PowerShell's Switch command to alter this code block, which will run on Monday:
for ($i = 1; $i -le 7; $i++)
{
$d = ((Get-Date).AddDays($i))
$d2 = ($d.ToString("M/dd/yyyy") + " " + "1:00 am".ToUpper())
$d3 = ($d.ToString("yyyy-MM-dd"))
$d4 = (($d).DayOfWeek).ToString("").ToUpper()
My-Function -date $d2 -day $d3 -dayofweek $d4
}
That code works as expected, however the difficulties come in when I'm trying to adjust things, as seen below:
$i=@(-1,0,1,2,3,4,5)
for ($i -le 7; $i++){
$d = ((Get-Date).AddDays($i))
$d2 = ($d.ToString("M/dd/yyyy") + " " + "1:00 am".ToUpper())
$d3 = ($d.ToString("yyyy-MM-dd"))
$d4 = (($d).DayOfWeek).ToString("").ToUpper()
}
But that code returns the following error text, also trying [int]$i=@(-1,0,1,2,3,4,5)
also doesn't work. That returns Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32".At line:1 char:1
The '++' operator works only on numbers. The operand is a 'System.Object[]'.At line:2 char:16
+ for ($i -le 7; $i++){
+ ~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : OperatorRequiresNumber
Upvotes: 0
Views: 3229
Reputation: 201592
That error is correct. $i is an array and you're trying to invoke the ++ operator on it and that is not supported. I think you want this
$array = -1,0,1,2,3,4,5
foreach ($i in $array) {
$d = (Get-Date).AddDays($i)
$d2 = $d.ToString("M/dd/yyyy") + " 1:00 AM"
$d3 = $d.ToString("yyyy-MM-dd")
$d4 = $d.DayOfWeek.ToString().ToUpper()
}
Upvotes: 3