3

I have a hashtable defined in powershell as below:

$jobs = @{
    "Test1"=[Array](
        [Array]("\\server1\file1.txt", "\\server2\file1.txt")

    );
    "Test2"=[Array](
        [Array]("\\sever1\file2.txt", "\\server2\file2.txt"),
        [Array]("\\server1\file3.txt", "\\server2\file3.txt")
    );
}

I am trying to enumerate over this collection and call a function on each pair. Test1 has 1 file comparison and Test2 has two file comparisons.

$jobs.GetEnumerator() | Sort-Object Key | foreach {
    LogWrite($_.Key + ": comparing files")

    $_.value | foreach {
        LogWrite("Comparing files '" + $_[0] + "' and '" + $_[1] + "'")
        #$r = CompareFiles($_[0], $_[1])
        #LogWrite("Result : " + $r)
    }

    LogWrite($_.Key + ": comparison successful")
    LogWrite("")
}

The output I am getting is:

Test1: comparing files
Comparing files '\' and '\'
Comparing files '\' and '\'
Test1: comparison successful

Test2: comparing files
Comparing files '\\server1\file2.txt' and '\\server2\file2.txt'
Comparing files '\\server1\file3.txt' and '\\server2\file3.txt'
Test2: comparison successful

Powershell (something) seems to be creating equal sized arrays. Can anyone suggest a better data structure or solution?

David
  • 15,150
  • 15
  • 61
  • 83
  • FWIW, Powershell seems to actually be *flattening* the first nested array `Test1`. – lc. Jan 02 '13 at 09:56
  • Related: http://stackoverflow.com/questions/2463190/avoiding-agnostic-jagged-array-flattening-in-powershell – lc. Jan 02 '13 at 09:58

1 Answers1

3

Referencing Avoiding Agnostic Jagged Array Flattening in Powershell, it would appear if you add a comma in the single-element array, it will stop it from being flattened:

$jobs = @{
    "Test1"=[Array](,
        [Array]("\\server1\file1.txt", "\\server2\file1.txt")

    );
    "Test2"=[Array](
        [Array]("\\sever1\file2.txt", "\\server2\file2.txt"),
        [Array]("\\server1\file3.txt", "\\server2\file3.txt")
    );
}

There must be something odd about the way arrays are handled in Powershell.

Community
  • 1
  • 1
lc.
  • 113,939
  • 20
  • 158
  • 187