PowerShell技术问题:如何从RDS会话主机FQDN中提取主机名
Let's break down why your initial approach wasn't working and how to fix it:
The Root Problem
Your first command uses Out-String, which converts the entire output (including table headers and separators) into a single multi-line string. When you loop through this string, you're processing every line (including "SessionHost" and "-----------") instead of just the FQDN values. This is why your substring/split attempts weren't producing the expected results.
Step 1: Get Clean Session Host Values
First, adjust your initial command to retrieve just the SessionHost FQDNs as an array of strings, not a formatted table:
$CB = "your-connection-broker-name" # Replace with your actual broker $SHs = Get-RDSessionCollection -ConnectionBroker $CB | ForEach-Object { Get-RDSessionHost -ConnectionBroker $CB -CollectionName $_.CollectionName } | Select-Object -ExpandProperty SessionHost
Using Select-Object -ExpandProperty SessionHost extracts the raw FQDN values into an array, so $SHs will look like:
SH1.contoso.com SH2.contoso.com SH3.contoso.com
Step 2: Truncate the Domain
Now you can process each FQDN to remove the domain suffix. Two reliable methods:
Method 1: Split on the first dot (most robust)
This works even if your domain length varies:
foreach ($SH in $SHs) { ($SH -split '\.')[0] }
Method 2: Use IndexOf to get everything before the first dot
foreach ($SH in $SHs) { $SH.Substring(0, $SH.IndexOf('.')) }
Either method will output exactly what you want:
SH1 SH2 SH3
Why Your Previous Split Attempt Failed
When you used $SH = ($SH -split "\.")[0] with the original $SHs (a multi-line string), you were splitting individual lines like "SessionHost" and "-----------" along with the FQDNs. The clean array from Step 1 ensures you only process valid hostnames.
内容的提问来源于stack exchange,提问作者Elo Bizne

