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

PowerShell多选列表框实现脚本选择执行需求问询

PowerShell多选列表框执行对应脚本实现方案

核心修改方向

你只需要替换列表选项为实际脚本名称,并在确认选中后添加脚本执行逻辑即可,以下是完整实现代码和关键说明:

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(350,220)
$form.StartPosition = 'CenterScreen'

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(85,140)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = '执行选中脚本'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(165,140)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = '取消'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)

$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(320,20)
$label.Text = '请选择要执行的脚本:'
$form.Controls.Add($label)

$listBox = New-Object System.Windows.Forms.Listbox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(320,80)
$listBox.SelectionMode = 'MultiExtended'

# 替换为你的4个脚本名称
[void] $listBox.Items.Add('备份数据脚本.ps1')
[void] $listBox.Items.Add('清理日志脚本.ps1')
[void] $listBox.Items.Add('系统信息收集脚本.ps1')
[void] $listBox.Items.Add('用户权限配置脚本.ps1')

$form.Controls.Add($listBox)
$form.Topmost = $true

$result = $form.ShowDialog()

if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
    foreach ($selectedItem in $listBox.SelectedItems) {
        $scriptName = $selectedItem.ToString()
        # 脚本路径:如果脚本和当前脚本同目录,用$PSScriptRoot;否则写绝对路径,比如"C:\Scripts\$scriptName"
        $scriptPath = Join-Path -Path $PSScriptRoot -ChildPath $scriptName
        
        # 先检查脚本是否存在,避免报错
        if (Test-Path -Path $scriptPath -PathType Leaf) {
            Write-Host "正在执行:$scriptName"
            & $scriptPath  # 执行选中的脚本
        }
        else {
            Write-Warning "未找到脚本:$scriptName,路径:$scriptPath"
        }
    }
}

关键说明

  1. 脚本路径处理:$PSScriptRoot代表当前脚本所在的文件夹,如果你的目标脚本在其他位置,直接替换成绝对路径即可,比如"D:\MyScripts\$scriptName"。
  2. 执行脚本:用&操作符调用脚本是PowerShell的标准方式,能正确处理脚本执行上下文。
  3. 错误预防:添加Test-Path判断脚本是否存在,避免因路径错误或文件缺失导致的执行报错。
  4. 界面调整:调整了窗体大小和列表框高度,适配4个选项的显示,你可以根据实际需求进一步修改尺寸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:15:22