如何从对象组中筛选含Move-In (Name)值的单个对象?
Filtering for the Object with Non-Empty 'Move-In (Name)' Field
To grab the single object where the Move-In (Name) field isn't empty, you just need to add an extra condition to your Where-Object clause. Since the property name includes spaces and parentheses, you'll need to use bracket notation to access it properly (PowerShell can get confused with special characters in dot notation).
Here are two adjusted commands to solve this:
# Basic version: filters out empty strings $rest.Group | Where-Object { $_.SERV_UNIT -eq '2704' -and $_.['Move-In (Name)'] -ne '' } | Select-Object * # More robust version: filters out both $null and empty strings $rest.Group | Where-Object { $_.SERV_UNIT -eq '2704' -and -not [string]::IsNullOrEmpty($_.['Move-In (Name)']) } | Select-Object *
Quick breakdown of the changes:
- Bracket notation for property access:
$_.['Move-In (Name)']ensures PowerShell correctly reads the property name with spaces and parentheses—dot notation would throw an error here. - Non-empty check: The
-ne ''condition removes objects whereMove-In (Name)is an empty string. The second version uses[string]::IsNullOrEmpty()to also handle cases where the property value is$null, making it more reliable. - Optimized pipeline order: We filter first before selecting all properties (
Select-Object *), which is more efficient than grabbing all properties first then filtering.
This will return exactly the single object you need, where Move-In (Name) has a value.
内容的提问来源于stack exchange,提问作者Simon Yo
相关产品推荐
相关产品推荐

