Read-Host变量在Select-Object中无法正常工作的问题
Hey there! I totally get why this is confusing—let’s break down what’s happening and fix it right away.
The Root Problem
When you type name,enabled into Read-Host, PowerShell stores that as a single string value (like "name,enabled"), not as separate property names. But Select-Object expects an array of individual property names (think: "name", "enabled"). So when you pass the variable directly, it’s trying to look for a single property named name,enabled—which doesn’t exist on AD objects, hence the empty {} result.
The Fix: Split the String into an Array
You just need to convert that comma-separated string into a proper array of property names. Here’s how to do it:
- First, capture the user input and split it into cleaned-up parts:
# Get input from the user $userInput = Read-Host "Enter AD properties separated by commas (e.g., name,enabled)" # Split the string by commas, then trim any extra spaces from each property name $propertyArray = $userInput -split ',' | ForEach-Object { $_.Trim() }
- Now pass this array to
Select-Object, and it’ll work exactly like when you type the properties manually:
Get-ADComputer CTXTEST | Select-Object $propertyArray
Bonus: Robust Edge Case Handling
If you want to make the script more resilient (like ignoring accidental extra spaces or trailing commas), add a filter to remove blank entries:
$propertyArray = $userInput -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }
This way, even if someone enters name , enabled , (with messy spaces and a trailing comma), it’ll still correctly target just the name and enabled properties.
内容的提问来源于stack exchange,提问作者Flying Thunder

