January 11th, 2007

Accessing data past the end of an array

PowerShell Team
PowerShell Team

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

Category
PowerShell

Author

PowerShell Team
PowerShell Team

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

0 comments

Discussion are closed.