Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my PowerShell multi dimensional array being interpreted as a 1 dimensional array?

I have the following code:

function HideTemplates($File, $Templates)
{
  foreach ($Template in $Templates)
  {
    Write-Host $Template[0] $Template[1] $Template[2]
  }
}

HideTemplates "test.xml" @(("one", "two", "three"))
HideTemplates "test.xml" @(("four", "five", "six"), ("seven", "eight", "nine"))

It prints:

o n e
t w o
t h r
four five six
seven eight nine

I want it to print:

one two three
four five six
seven eight nine

Am I doing something wrong in my code? Is there a way to force PowerShell to tread a multi-dimensional array with a single item differently?

like image 747
Jim Avatar asked May 21 '10 17:05

Jim


People also ask

How do I create a multi-dimensional array in PowerShell?

Syntax of PowerShell Multidimensional Array So for example, if we need an array of numbers than we can define int32, in the same way, if we need an array with string then we can define with string. $array = @( @(“data2”), @(“data3”), @(“data4”) …….)

How can you tell if an array is multidimensional?

Checking for the element at index 0, we can tell whether the array is multidimensional or not.


1 Answers

Call your function like so:

HideTemplates "test.xml" (,("one", "two", "three"))
HideTemplates "test.xml" (,("four", "five", "six"),("seven", "eight", "nine"))

An array subexpression ie @() does nothing if the contents are already an array. Use the comma operator instead which will always create an array with one element around whatever follows it. Note that you have to add an extra set of parens otherwise this:

HideTemplates "test.xml",("one", "two", "three")

Would be considered a single argument of type array instead of two arguments.

like image 110
Keith Hill Avatar answered Oct 26 '22 15:10

Keith Hill