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

如何在PowerShell输出中添加单选按钮或实现项目选择功能?

PowerShell 选择输出项执行后续操作的实现方法

用 Out-GridView 实现单选并执行操作

Out-GridView 默认支持多选,要开启单选模式,只需要加上 -OutputMode Single 参数。选中项目后,就能把结果赋值给变量,再执行后续操作,比如终止进程:

# 弹出进程列表窗口,限制只能单选
$selectedProcess = Get-Process | Out-GridView -Title "选择要终止的进程" -OutputMode Single

# 只有选中了进程才执行终止操作,避免空值报错
if ($selectedProcess) {
    Stop-Process -Id $selectedProcess.Id -Confirm:$false
    Write-Host "已终止进程: $($selectedProcess.Name)"
}

如果需要支持多选,把 -OutputMode 的值改成 Multiple 即可,后续遍历变量里的集合逐个处理就行。

其他可选的选择方式

1. 命令行输入选择

如果不想弹出图形窗口,可以用 Read-Host 让用户输入进程ID或名称,再筛选执行:

# 先列出所有进程的名称和ID,方便用户参考
Get-Process | Select-Object Name, Id | Format-Table -AutoSize

$inputValue = Read-Host "请输入要终止的进程ID或名称"

# 根据输入匹配目标进程
$targetProcess = Get-Process | Where-Object { $_.Id -eq $inputValue -or $_.Name -eq $inputValue }

if ($targetProcess) {
    Stop-Process -InputObject $targetProcess -Confirm:$false
    Write-Host "已终止进程: $($targetProcess.Name)"
} else {
    Write-Host "未找到匹配的进程,请检查输入"
}

2. 自定义Windows Forms单选界面

如果需要更个性化的单选界面,可以用Windows Forms构建自定义窗口,灵活性更高:

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# 创建主窗体
$form = New-Object System.Windows.Forms.Form
$form.Text = "选择要终止的进程"
$form.Size = New-Object System.Drawing.Size(400, 500)
$form.StartPosition = "CenterScreen"

# 创建进程列表分组框
$groupBox = New-Object System.Windows.Forms.GroupBox
$groupBox.Text = "进程列表"
$groupBox.Location = New-Object System.Drawing.Point(10, 10)
$groupBox.Size = New-Object System.Drawing.Size(360, 400)
$form.Controls.Add($groupBox)

# 为每个进程生成单选按钮
$yPos = 20
Get-Process | Sort-Object Name | ForEach-Object {
    $radioBtn = New-Object System.Windows.Forms.RadioButton
    $radioBtn.Text = "$($_.Name) (ID: $($_.Id))"
    $radioBtn.Location = New-Object System.Drawing.Point(20, $yPos)
    $radioBtn.Tag = $_.Id  # 把进程ID存在Tag属性里,方便后续调用
    $groupBox.Controls.Add($radioBtn)
    $yPos += 25
}

# 创建确认按钮
$okBtn = New-Object System.Windows.Forms.Button
$okBtn.Text = "确认终止"
$okBtn.Location = New-Object System.Drawing.Point(150, 420)
$okBtn.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $okBtn
$form.Controls.Add($okBtn)

# 显示窗口并获取用户选择
$result = $form.ShowDialog()

if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
    $selectedId = $groupBox.Controls | Where-Object { $_.Checked } | Select-Object -ExpandProperty Tag
    if ($selectedId) {
        Stop-Process -Id $selectedId -Confirm:$false
        Write-Host "已终止进程ID: $selectedId"
    }
}

# 释放窗体资源
$form.Dispose()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:54:31