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

WPF新手求助:如何将PowerShell输出转为无表头DataGrid

问题解决:WPF DataGrid 2列无表头展示PowerShell数据

你的代码核心问题是对WPF DataGrid的使用逻辑错误:$agfCustom是单个自定义对象,直接遍历它会将整个对象作为单行的单个元素,且DataGrid默认会根据对象属性自动生成多列,不符合你要2列(属性名+属性值)、无表头的需求。以下是修正方案:

关键修改点

  • 修改DataGrid的XAML配置,隐藏表头并定义固定两列
  • 将自定义对象转换为键值对集合,作为DataGrid的数据源
  • 改用数据源绑定的方式填充数据,替代错误的Rows.Add逻辑

修改后的完整脚本

#-------------------------------------------------------------#
#----Initial Declarations-------------------------------------#
#-------------------------------------------------------------#

Add-Type -AssemblyName PresentationCore, PresentationFramework

$Xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="800" Height="400">
<Grid>
 <Button Content="查询" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="266,30,0,0" Name="leznbuixc7f7z"/>

<TextBox HorizontalAlignment="Left" VerticalAlignment="Top" Height="23" Width="120" TextWrapping="Wrap" Margin="42,33,0,0" Name="userName" ToolTip="输入用户名"/>
<!-- 修改DataGrid配置:隐藏表头,定义固定两列 -->
<DataGrid HorizontalAlignment="Left" VerticalAlignment="Top" Width="326" Height="211" Margin="375,103,0,0" 
          Name="DataGridView1" HeadersVisibility="None" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <!-- 第一列:属性名 -->
        <DataGridTextColumn Header="属性" Width="120" Binding="{Binding Key}"/>
        <!-- 第二列:属性值 -->
        <DataGridTextColumn Header="值" Width="*" Binding="{Binding Value}"/>
    </DataGrid.Columns>
</DataGrid>
</Grid></Window>
"@

#-------------------------------------------------------------#
#----Control Event Handlers-----------------------------------#
#-------------------------------------------------------------#

function OnClick {
    # 查询用户关联主机名
    $Computernames = Get-Content -Path "\\data\PC.csv" |    
                     Select-Object -Skip 3 |       
                     ConvertFrom-Csv  -Delimiter ","

    $pcNamecsv = $Computernames.Where({ $_."Details_Table0_User_Name0" -eq $userName.Text})."Details_Table0_Name0" | Where { $_ -like 'BNL0*' -or $_ -like 'BNL5*'}

    $ADcomputing = @('Name','LastLogonDate')
    $ADproperty = foreach ($PC in $pcNamecsv) {
        Get-ADcomputer $PC -Properties $ADcomputing
    } 
    $pcName = ($ADproperty | Sort LastLogonDate -Descending | Select -First 1).Name

    # 查询AD用户属性
    $agfProperties = @(
        'Name','mail','OfficePhone','Description','PasswordLastSet',
        'LastBadPasswordAttempt','LockedOut','Enabled','msDS-UserPasswordExpiryTimeComputed','Givenname'
    )
    $agfUser = Get-Aduser -Identity $userName.Text -Properties $agfProperties

    $agfExpiry = Get-ADUser -identity $userName.Text –Properties  "msDS-UserPasswordExpiryTimeComputed" |
                Select-Object -Property @{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} | 
                select -expandproperty "ExpiryDate" -first 1 
                  
    # 创建自定义对象
    $agfCustom = [pscustomobject]@{   
        UserID                      = $agfUser.Name
        Mail                        = $agfUser.mail
        Phone                       = $agfUser.OfficePhone
        Hostname                    = $pcName
        LockedStatusAGF             = $agfUser.LockedOut
        AccountEnabledAGF           = $agfUser.Enabled
        LastBadPasswordAttemptAGF   = $agfUser.LastBadPasswordAttempt
        PasswordExpiresAGF          = $agfExpiry
        PasswordLastSetAGF          = $agfUser.PasswordLastSet
    }

    # 将自定义对象转换为键值对集合,作为DataGrid数据源
    $dataSource = $agfCustom | Get-Member -MemberType NoteProperty | ForEach-Object {
        [pscustomobject]@{
            Key = $_.Name
            Value = $agfCustom.$($_.Name)
        }
    }

    # 绑定数据源到DataGrid
    $DataGridView1.ItemsSource = $dataSource
}

#-------------------------------------------------------------#
#----Script Execution-----------------------------------------#
#-------------------------------------------------------------#

$Window = [Windows.Markup.XamlReader]::Parse($Xaml)
[xml]$xml = $Xaml
$xml.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name $_.Name -Value $Window.FindName($_.Name) }

$leznbuixc7f7z.Add_Click({OnClick $this $_})
$Window.ShowDialog()

说明

  1. XAML部分:给DataGrid添加HeadersVisibility="None"隐藏表头,关闭AutoGenerateColumns并手动定义两列,分别绑定键值对的Key和Value
  2. 数据转换:使用Get-Member提取自定义对象的属性名和对应值,转换成键值对集合,让DataGrid按2列展示
  3. 数据源绑定:直接将键值对集合赋值给DataGrid的ItemsSource,这是WPF数据绑定的标准方式,比手动添加行更可靠

内容的提问来源于stack exchange,提问作者Toon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:00:01