Accessing data past the end of an array

Accessing data past the end of an array

  • Comments 1

In the newsgroup Microsoft.Public.Windows.PowerShell  Marco Shaw asked about accessing data past the end of a defined array.  He wondered why he didn't get an error.   

As a general rule in PowerShell, when you ask for something that doesn't exist, you get an NULL not an error.


 
PS> $array=@(0,1,2)
PS> if ($array[1] -ge $array[50000]) {"ge"}
ge
PS> if ($array[1] -ge $NoSuchVariable) {"ge"}
ge
PS>
 

The exception to this rule is when you enable STRICT mode.  STRICT mode is limited in V1, it throws an exception when you access a variable that does not exist.  But it does not throw an exception if you access an array element which does not exist.  Over time, we'll address that.


 
PS> Set-PSDebug -Strict
PS> $array=@(0,1,2)
PS> if ($array[1] -ge $NoSuchVariable) {"ge"}
The variable $NoSuchVariable cannot be retrieved because it has not been se
t yet.
At line:1 char:34
+ if ($array[1] -ge $NoSuchVariable) <<<<  {"ge"}
PS> if ($array[1] -ge $array[50000]) {"ge"}
ge
PS>


Jeffrey Snover [MSFT]
Windows PowerShell/MMC Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Leave a Comment
  • Please add 7 and 7 and type the answer here:
  • Post
  • Just a clarification: STRICT mode technically throws an exception when you try to access a variable which hasn't had a value set yet, correct? Which is different in a minor way from a variable that doesn't yet *exist* - although in PowerShell you can't technically "create" a variable without also setting a value to it, so *practically* it's the same thing. I guess, pointing out the difference from languages like VBScript where you can Dim a variable, but not have assigned a value to it; in other words, STRICT isn't *quite* like Option Explicit. Right?

Page 1 of 1 (1 items)