Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cannot index into null array

Status
Not open for further replies.

doooolaney

Programmer
Jan 25, 2011
2
GB
Hi, I've just joined here because it looks like a good place to troubleshoot PowerShell (which I've just started to learn) and I'll be doing some Android programming at some point so I'm sure I'll be needing all you guys help.

Ok...My problem is that the code below brings about the dreaded cannot index into null array error when using the $ListOfUsers variable.

Does anyone have any ideas how I resolve this or rewrite the code to work better?

Cheers.

NOTE: All variable instances not initialised have been done so in the code elsewhere
Code:
# Store the list of users due to expire
$ListOfUsers[0]
$Count = -1
# If the user's account is due or almost due to expire then capture details of account into an array 
if (($DaysLeft -eq $NumOfDays) -or ($DaysLeft -le $NumOfDays) -and ($DaysLeft -ge 0) -or ($DaysLeft -le 0)) { 
            
  $ListOfUsers[$Count++] = $Users.Name
  $ListOfUsers[$Count++] = $Users.Email
  $ListOfUsers[$Count++] = $ExpiredDate
  $ListOfUsers[$Count++] = $DaysLeft
}
 
What is the standalone line
$ListOfUsers[0]
supposed to accomplish?

Your If statement is also too complex. Based on this code it should just read:
If ($DaysLeft -le $NumOfDays)

-le stands for "Less than or Equal", so that covers your first clause testing just for equal. Your last two clauses comparing $DaysLeft to 0 mean $DaysLeft can be any number including 0. Unless there was something else you were trying to test for those last two clauses aren't needed.
 
$ListOfUsers[0] was my thinking of how you initialise an array

I've since learned elsewhere that this is accomplished with
$ListOfUsers = @( )

But now when I reference the array, I get the error:
Array assignment failed because index '0' was out of range.

Basically, how do I create an array that I can then store information in like the following

$ListOfUsers[0] = "Peter"
$ListOfUsers[1] = "Michael"
$ListOfUsers[2] = "John"

Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top