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

如何用PowerShell实现文本框添加用户名至数组并表格展示

PowerShell 实现用户名收集窗体并表格展示

需求

  • 通过Windows窗体将用户名(名字)添加到数组中
  • 使用文本框作为名字输入控件
  • 点击按钮完成每次输入操作
  • 最终将所有输入数据以表格格式展示

现有尝试代码

$usernames = @()
$usernames += [pscustomobject]@{
Firstnames=$firstname  
}

$form = New-object System.Windows.Forms.Form
$form.Location = "500, 500"
$form.Text = "Add User names"

$textbox = New-object System.Windows.Forms.Textbox 
$textbox.Location = "55, 130"
$textbox.size = "114, 40"
$textbox.text = ""

$button = New-object System.Windows.Forms.Button
$button.Location = "55, 150"
$button.size = "155, 23"
$button.text = Add User name


$button.Add_Click = {($firstname = $textbox.text)}

$form.controls.Add($button.Add_Click)
$form.controls.Add($textbox)
$form.ShowDialog() | Out-null

问题分析与修复

现有代码存在几个关键问题:

  1. 变量作用域错误:点击事件中的变量无法正确访问脚本级的$usernames数组
  2. 按钮事件逻辑缺失:仅获取文本框内容,未将其添加到数组
  3. 控件添加错误:错误地将点击事件方法添加到窗体控件集合,应添加按钮对象本身
  4. 语法错误:按钮文本未加引号,会导致运行报错
  5. 初始数组操作无效:初始化时就添加了未定义的$firstname对象,导致数组初始为空对象

以下是修复后的完整代码:

# 初始化空数组用于存储用户名
$usernames = @()

# 创建窗体
$form = New-Object System.Windows.Forms.Form
$form.Location = New-Object System.Drawing.Point(500, 500)
$form.Text = "添加用户名"
$form.Size = New-Object System.Drawing.Size(300, 250)

# 创建输入文本框
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.Location = New-Object System.Drawing.Point(55, 50)
$textbox.Size = New-Object System.Drawing.Size(180, 20)
$textbox.PlaceholderText = "请输入名字"

# 创建添加按钮
$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Point(55, 80)
$button.Size = New-Object System.Drawing.Size(180, 23)
$button.Text = "添加用户名"

# 按钮点击事件:将文本框内容添加到数组,清空文本框
$button.Add_Click({
    if (-not [string]::IsNullOrWhiteSpace($textbox.Text)) {
        $newUser = [pscustomobject]@{
            FirstName = $textbox.Text.Trim()
        }
        # 使用Script:前缀访问脚本级变量
        $script:usernames += $newUser
        $textbox.Clear()
        $textbox.Focus()
    }
})

# 创建关闭按钮,用于结束输入并展示表格
$closeButton = New-Object System.Windows.Forms.Button
$closeButton.Location = New-Object System.Drawing.Point(55, 120)
$closeButton.Size = New-Object System.Drawing.Size(180, 23)
$closeButton.Text = "完成输入并展示"
$closeButton.Add_Click({
    $form.Close()
})

# 将控件添加到窗体
$form.Controls.Add($textbox)
$form.Controls.Add($button)
$form.Controls.Add($closeButton)

# 显示窗体
$form.ShowDialog() | Out-Null

# 展示收集到的用户名表格
if ($usernames.Count -gt 0) {
    Write-Host "收集到的用户名:"
    $usernames | Format-Table -AutoSize
} else {
    Write-Host "未收集到任何用户名"
}

修复说明

  • 使用Script:前缀确保点击事件能正确修改脚本级的$usernames数组
  • 添加输入验证,避免空值或空白字符被添加
  • 新增“完成输入并展示”按钮,明确结束输入的操作
  • 使用System.Drawing.Point和System.Drawing.Size更规范地设置控件位置和大小
  • 窗体关闭后自动输出收集到的用户名表格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 22:12:50