基于唯一属性将数组拆分为独立对象的技术咨询
Split PowerShell Array into Independent Objects by Unique Property
Based on your sample DSC configuration results, here's a practical way to split your array into separate logical groups/objects using a unique property:
Step 1: Assume your array is stored in a variable
First, let’s say your existing array is saved in $dscResults (swap this with your actual variable name):
# Example matching your sample data $dscResults = @( [PSCustomObject]@{ PSComputerName = "server1.domain.local" ResourceName = "WindowsFeature" InstanceName = "Backup" InDesiredState = $true ConfigurationName = "BaseConfig" StartDate = [DateTime]"24/04/2018 14:31:23" }, [PSCustomObject]@{ PSComputerName = "server1.domain.local" ResourceName = "Registry" InstanceName = "fDenyTSConnections" InDesiredState = $true ConfigurationName = "BaseConfig" StartDate = [DateTime]"24/04/2018 14:31:23" }, [PSCustomObject]@{ PSComputerName = "server1.domain.local" ResourceName = "Registry" InstanceName = "UserAuthentication" InDesiredState = $true ConfigurationName = "BaseConfig" StartDate = [DateTime]"24/04/2018 14:31:23" } )
Step 2: Group the array by your target unique property
Use Group-Object to cluster items by the property you want to split on. For example, splitting by ResourceName:
$groupedResults = $dscResults | Group-Object -Property ResourceName
Step 3: Extract independent collections
Each group in $groupedResults contains all items matching that unique property value. You can pull them into separate variables for easy use:
# Isolate all WindowsFeature entries $windowsFeatureSet = $groupedResults | Where-Object Name -eq "WindowsFeature" | Select-Object -ExpandProperty Group # Isolate all Registry entries $registrySet = $groupedResults | Where-Object Name -eq "Registry" | Select-Object -ExpandProperty Group
Alternative: Use a hashtable for quick lookup
If you want instant access to any group by its property value, convert the grouped results into a hashtable:
$splitLookup = @{} $dscResults | Group-Object -Property ResourceName | ForEach-Object { $splitLookup[$_.Name] = $_.Group } # Access groups directly by property value $splitLookup["WindowsFeature"] # Returns all WindowsFeature items $splitLookup["Registry"] # Returns all Registry items
Key Notes
- Replace
ResourceNamewith whatever unique property you need (e.g.,InstanceNameif each instance is distinct). - If you need individual items as standalone objects instead of grouped sets, you can iterate over the original array directly, but grouping is far more efficient for logical splits.
内容的提问来源于stack exchange,提问作者PnP
相关产品推荐
相关产品推荐

