Looping through a hashtable referencing a second hashtable

Welcome Forums General PowerShell Q&A Looping through a hashtable referencing a second hashtable

This topic contains 3 replies, has 2 voices, and was last updated by

 
Moderator
3 months, 2 weeks ago.

  • Author
    Posts
  • #132108

    Participant
    Points: 17
    Rank: Member

    I am trying to write a script to back up user data. I have two hashtables, one named $Locations that contains the directory name and the corresponding directory location (e.g. "Data" = "C:\Data"), and a hashtable named $Destinations that contains the destination pairs built from user responses (e.g. "Data" = "D:\Data". I cannot figure out how to loop through the $Locations hashtable and reference the $Destinations hashtable at the same time. If I use the below code, it gives me the $Locations data as I want it, but I cannot do anything with the $Destinations.

    ForEach ($Source in $Locations.Values) {
    Write-Host $Source
    }

    If I leave off the .Values in the ForEach, so that I can try to reference the Destination, then I just get one big blob of all the data separated by spaces. Advice is greatly appreciated, thanks.

  • #132116

    Moderator
    Points: 1,976
    Helping Hand
    Rank: Community Hero

    What are you actually trying to do with these hashtables. Can you explain the actions you would perform with these hashtables in bullet points below for us to understand it.

  • #132128

    Participant
    Points: 17
    Rank: Member

    I am trying to loop through them for source/destination pairs and pass that to Robocopy.

    Shortly after I posted this, it hit me to use the following:

    Assuming the $Locations hashtable has an entry "Data" = "C:\Data" and the $Destinations hashtable ends up having an entry of "Data" = "D:\Data" after user input. I ran through the following loop:

    ForEach ($Source in $Locations.Keys) { Robocopy $Locations["$Source"] $Destinations["$Source"] }

    and it came out with my desired line, "Robcopy C:\Data D:\Data"

    .Keys ended up being the property I was looking for.

    Thanks for the replies!

  • #132149

    Moderator
    Points: 1,976
    Helping Hand
    Rank: Community Hero

    Great to know that you figured it out yourself.

The topic ‘Looping through a hashtable referencing a second hashtable’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort