Home > Back-end >  Correctly Enumerating through a Hashtables values in a ForEach-Object Loop
Correctly Enumerating through a Hashtables values in a ForEach-Object Loop

Time:08-27

Firstly the Hashtable (Called $MyHashTable) looks like this:

Name                           Value
----                           -----
NTER 1                         {[Short, Kill > Dump], [Long, Procces is terminated, then all errors are dumped to a log file1]}
NTER 2                         {[Short, Kill > Dump], [Long, Procces is terminated, then all errors are dumped to a log file2]}
NTER 3                         {[Short, Kill > Dump], [Long, Procces is terminated, then all errors are dumped to a log file3]}
NTER 4                         {[Short, Kill > Dump], [Long, Procces is terminated, then all errors are dumped to a log file4]}
LA2 1                          {[Short, Kill > Dump], [Long, Procces is terminated, then all errors are dumped to a log file5]}
LA2 2                          {[Short, Kill > Dump], [Long, Procces is terminated, then all errors are dumped to a log file6]}
LA2 3                          {[Short, Kill > Dump], [Long, Procces is terminated, then all errors are dumped to a log file7]}
LA2 4                          {[Short, Kill > Dump], [Long, Procces is terminated, then all errors are dumped to a log file8]}

I want to use this Hashtable in a ForEach-Object loop, where $MyHashTable.Name will be used as a name for the file in the loop, and $MyHashTable.values.long will be used as MetaData for this same file. The output should be:

In a my file manager:

Here is a snippet of my code (the part where the files are being generated):

    $MyHashTable.keys | ForEach-Object {

        # First Copy the files to their folder

        Copy-item -path 'C:\Temp\Template 2.svg' -Destination "C:\Temp\$_.svg"

        foreach ($Key in $MyHashTable.values.long) {

            # Then Populate their Column Data

            set-metadata  -path "C:\Temp\$_.svg" -Misc1 $key}
            }

The files copy fine with the desired names but foreach ($Key in $MyHashTable.values.long) loop just gives every file the same MetaData Value ("Procces is terminated, then all errors are dumped to a log file1" Each of these commands and expressions (Set-MetaData, $MyHashTable.values.long etc ) work just fine indvidually on their own. Just putting them together...

I've litterally been at this for hours and tried a number of things: diagnosing the issue, searching stackoverflow for alternatives etc I cannott get around. So close... Please help!

CodePudding user response:

I’ve read your different posts and it seems you simply need to do this

$MyHashTable.keys | ForEach-Object {

    # First Copy the files to their folder
    Copy-item -path 'C:\Temp\Template 2.svg' -Destination "C:\Temp\$_.svg"

    # Then Populate their Column Data
    set-metadata  -path "C:\Temp\$_.svg" -Misc1 $MyHashTable[$_].long
}
  • Related