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

PowerShell技术问题:如何从RDS会话主机FQDN中提取主机名

Fixing Session Host FQDN Truncation in PowerShell

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:52:30