Update-List – ever used ?

PowerShell 7 brought the Update-List CmdLet back and i was curious what it does (Psssst !!! – i never used it before either …).

See the below example based on a simple PSObject with 3 list-type properties and identify the value of Update-List.

Environment: PowerShell 7-RC1, Windows 64-Bit

The Sample Data

First of all – with Update-List you are able to manipulate object properties which are list-type. It is not possible to manage list-type objects themself. With this in mind (ok, i did read the documentation) i created a sample object as shown above.

Step 1 – Create the lists

# Create Lists - 3 ways, same results
$names = New-Object System.Collections.Generic.List[string]]
$names.Add("Anna")
$names.Add("Bob")
$names.Add("Charlie")

$cities = [System.Collections.Generic.List[string]]::New()
$cities.Add("Vienna")
$cities.Add("Munic")
$cities.Add("Zurich")

$jobs = [System.Collections.Generic.List[string]]::New()
[string[]]$jobrange = 'Admin','Sales','Engineer' 
$jobs.AddRange($jobrange)

Step 2 – Create the data object with lists as properties

# Create Hashtable with lists
$data = @{
    Names = $names
    Cities = $cities
    Jobs = $jobs
}
# Create PS Object
$people = New-object psobject -Property $data

Now we can look into our object and explorer it.

Cv-C:> $people

Cities                  Jobs                     Names
------                  ----                     -----
{Vienna, Munic, Zurich} {Admin, Sales, Engineer} {Anna, Bob, Charlie}

Step 3 – Manipulate a list

Now lets do some data manipulation and add a list-entry called „Eric“ to the names property.

Cv-C:> Update-List -InputObject $people -Property Names -Add 'Eric'

Cities                  Jobs                     Names
------                  ----                     -----
{Vienna, Munic, Zurich} {Admin, Sales, Engineer} {Anna, Bob, Charlie, Eric}

Cv-C:\Users\roman.THEGALAXY> $people.Names
Anna
Bob
Charlie
Eric

Removing an entry is also possible with -Remove parameter.

Cv-C:> Update-List -InputObject $people -Property Names -Remove 'Anna'|Select-Object -Expandproperty Names
Bob
Charlie
Eric

Step 4 – Replacing a whole property

Lets say we want to get rid of the entries in the „cities“ property and replace them with new values. See below.

Cv-C:> # Replace by creating a new list object
$uscities = [System.Collections.Generic.List[string]]::New()
$uscities.Add("New York")
$uscities.Add("Chicago")
$uscities.Add("Seattle")
$uscities.Add("Dallas")
# and later on replace cities with uscities
Update-List -InputObject $people -Property cities -Replace $uscities |Select-Object Cities

Cities
------
{New York, Chicago, Seattle, Dallas}

Summary

Update-List makes it very easy to modify list-type properties in existing PSOjects with its Add-, Remove- and Replace- capability.

Have fun using it !

R.

Leave a Reply