David
David

Reputation: 15350

How to enumerate a hash in powerhshell where the values are arrays of strings

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?

Upvotes: 3

Views: 207

Answers (1)

lc.
lc.

Reputation: 116458

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.

Upvotes: 3

Related Questions