Coding Ref

The difference between -ExpandProperty and -Property in PowerShell

The difference between -ExpandProperty and -Property in PowerShell

The -Property parameter of the Select-Object cmdlet in PowerShell allows you to specify one or more properties of an object that you want to include in the output.

This parameter is used to filter the properties of an object, and only the specified properties will be included in the output.

In contrast, the -ExpandProperty parameter of the Select-Object cmdlet allows you to specify a property of an object that contains an array of values, and expand the values of that array into multiple objects, one for each value.

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

Example

Here is an example that demonstrates the difference between these two parameters:

# 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)
}

# Use -Property to filter the properties of the object

$object | Select-Object -Property Prop1, Prop3

# Use -ExpandProperty to expand the values of Prop4 into individual objects

$object | Select-Object -ExpandProperty Prop4

In this example, we use the -Property parameter to filter the properties of the object and include only Prop1 and Prop3 in the output. Then, we use the -ExpandProperty parameter to expand the values of Prop4 into individual objects. As a result, the output is different depending on which parameter is used.

Conclusion

The -Property parameter is used to filter the properties of an object, while the -ExpandProperty parameter is used to expand the values of a property that contains an array.

These two parameters can be used together or independently to manipulate the properties of an object in PowerShell.

You'll also like

Related tutorials curated for you

    How to use SFTP in PowerShell

    How to get the date in PowerShell

    Dictionaries in PowerShell

    What is a Scriptblock in PowerShell?

    How to print output in PowerShell

    Add-Content in PowerShell

    What are classes in PowerShell?

    How to install PowerShell on Mac

    How to add a user to a group in PowerShell

    How to use Format-Table in PowerShell

    How to get processes in PowerShell

    How to sort in PowerShell