0

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

1 Answer 1

3

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()
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yup yup, after much begging and yelling at PowerShell, I recalled foreach and now I know you can run foreach against a collection of numbers! Thanks @Keith

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.