首页 > 解决方案 > Two arrays, replacing the ID in one with the description of the other (matching ids) Powershell

问题描述

Im new to PowerShell, currently in the process of Learning, hope you guys can help me out.

I currently have what I understand are 2 arrays I can call their properties and positions with $ticket.id[0] , $categories.name[0] etc:

Ticket List

name: TicketName

Category ID: 1

Name: TicketName2

Category ID: 3


Categories

Category ID: 1

Name: Networking

Category ID: 3

Category Name: Printer

I would like to replace the value in Category ID (Ticket List) for the actual name on every ticket, currently I have tried for eachs and compare but have only gotten it to write all names into the id field.

Would appreciate any assistance.

标签: powershell

解决方案


There are a lot of different ways to attack a problem like this. However I would suggest first understanding what you are doing. You need a relationship between the data in was set versus the other. You need to go through each record in the $Tickets array, find the correct data from the $Categories array and reassign it to the correct property of the current object in the $Tickets array.

A great way to do this is to use a hash table. You can think of this as a table of key value pairs, I like to think of it as an index. A hash would facilitate multiple approaches as it merely provides a way to look up one value by another. This would also bear some similarity to a record's key field in a DB system like SQL.

Example:

# Simulates your description of the ticket array.
$tickets =
@(
    [PSCustomObject]@{
        Name = 'Mr. Jones Ticket'
        'Category ID' = 1
    }
    [PSCustomObject]@{
        Name = 'Mrs. Smith Ticket'
        'Category ID' = 2
    }
)

# Simulates your description of the categories array.
$Categories =
@(
    [PSCustomObject]@{
        'Category ID' = 1
        Name = 'Networking'
    }
    [PSCustomObject]@{
        'Category ID' = 2
        Name = 'Printer'
    }
)

# Create a Hash Table so you can relate the 2 sets of objects.
# Use the presumably unique Category ID as the key and the name 
# as the value.
$CategoryIndex = @{}
$Categories | 
ForEach-Object{
    $CategoryIndex.Add( $_.'Category ID', $_.Name)
}

# For each object in the $Tickets array lookup the category name from the new 
# CategoryIndex hash table and set the Category ID property of the current object
$Tickets |
ForEach-Object{
    $_.'Category ID' = $CategoryIndex[$_.'Category ID']
}

# Output the $Ticket array to demonstrate the the Category ID property 
# no holds the name not the number.
$Tickets

There are probably lots of ways to do this, but this is straight forward. Moreover, hash used lots of things in PowerShell & you are just starting out I think this is the best way for now.


推荐阅读