Coding Ref

What is PowerShell ExpandProperty?

What is PowerShell ExpandProperty?

PowerShell's ExpandProperty cmdlet allows you to expand the values of a property that contains an array of values into multiple objects, one for each value in the array.

This can be useful when working with complex or nested objects, as it allows you to access individual values within the object more easily.

Examples

Here is an example of how ExpandProperty can be used:

# Create a sample object with nested arrays
$object = [PSCustomObject]@{
    Prop1 = "Value1"
    Prop2 = "Value2"
    Prop3 = [PSCustomObject]@{
        NestedProp1 = 1
        NestedProp2 = 2
        NestedProp3 = 3
    }
    Prop4 = @(4, 5, 6)
}

# Output the object as-is
$object

# Use ExpandProperty to expand the values of Prop4 into individual objects
$object | Select-Object -ExpandProperty Prop4

In this example, $object is a custom PowerShell object with nested arrays. When we output the object using $object, it is displayed in its original form, with Prop4 shown as an array of values. However, when we use ExpandProperty to expand the values of Prop4, the values are expanded into individual objects, allowing us to access each value individually.

You can also use ExpandProperty to expand nested properties within an object. For example:

# Use ExpandProperty to expand the values of a nested property
$object | Select-Object -ExpandProperty Prop3 | Select-Object -ExpandProperty NestedProp1

In this example, we first use ExpandProperty to expand the values of the Prop3 property, which contains a nested object. Then, we use ExpandProperty again to expand the values of the NestedProp1 property within the nested object, allowing us to access the individual values.

Conclusion

ExpandProperty is a useful cmdlet for working with complex objects in PowerShell, and can make it easier to access and manipulate individual values within an object.

You'll also like

Related tutorials curated for you

    How to use String Contains in PowerShell

    Add-Content in PowerShell

    What are the different PowerShell file types?

    How to ping in PowerShell

    String formatting in PowerShell

    Dictionaries in PowerShell

    How to create new items in PowerShell

    What is `ls` for PowerShell?

    How to get the string length of a variable in PowerShell

    PowerShell vs. Bash

    What is IEX in PowerShell?

    How to find the Windows version from the PowerShell command line