You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Read-Host变量在Select-Object中无法正常工作的问题

Fixing the Select-Object Issue with Read-Host Input in PowerShell

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:

  1. 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() }
  1. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:36:41