Out-GridView配合上下文菜单

3
我想将上下文菜单与一个 Out-GridView 窗口关联起来。似乎 Out-GridView 没有本地的方法来实现这一点。
以下是一个 Out-DataGrid 函数。
下面是一个示例,其中文件夹项目被传递到 Out-DataGrid 中。要显示的属性被传递给了 Out-DataGrid。定义了一个上下文菜单,提供了几个操作:
ls 'C:\Windows' | 
    Out-DataGrid FullName, Extension, Mode, Attributes, LastWriteTime `
    -context_menu_items `
    @{ 
        name = 'Explorer'
        action = { param($dg) explorer $dg.SelectedItem.FullName } 
    }, 
    @{ 
        name = 'Notepad'
        action = { param($dg) notepad $dg.SelectedItem.FullName }
    },
    @{
        name = 'Run'
        action = { param($dg) & $dg.SelectedItem.FullName }
    }

生成的窗口和上下文菜单:

在此输入图片描述

列出后台作业的另一个例子:

Get-Job | Out-DataGrid Id, Name, State, HasMoreData, Command -context_menu_items `
    @{ 
        name = 'Receive'
        action = { param($dg) Receive-Job -Keep $dg.SelectedItem | Out-GridView } 
    },
    @{ 
        name = 'Remove'
        action = { param($dg) Remove-Job $dg.SelectedItem } 
    }

生成的窗口:

在此输入图片描述

我的问题是,有没有更好的方法来完成这个任务?

[void][System.Reflection.Assembly]::LoadWithPartialName('PresentationFramework')

function Out-DataGrid ($properties, $context_menu_items)
{
    $data_grid = New-Object -TypeName System.Windows.Controls.DataGrid -Property @{
        IsReadOnly = $true
        AutoGenerateColumns = $false
    }

    foreach ($elt in $properties)
    {
        $data_grid.Columns.Add((New-Object -TypeName System.Windows.Controls.DataGridTextColumn `
            -Property @{
                Header = $elt
                Binding = (New-Object System.Windows.Data.Binding -ArgumentList @(, $elt))  
            }))
    }

    $data_grid.ItemsSource = @($input)

    if ($context_menu_items)
    {
        $data_grid.ContextMenu = New-Object -TypeName System.Windows.Controls.ContextMenu

        foreach ($elt in $context_menu_items)
        {
            $menu_item = New-Object -TypeName System.Windows.Controls.MenuItem

            $menu_item.Header = $elt.name

            $menu_item.Add_Click({ 

                param($sender, $event_args)

                $elt.action.Invoke($data_grid)                        

            }.GetNewClosure())

            $data_grid.ContextMenu.AddChild($menu_item)
        }
    }

    $grid = New-Object System.Windows.Controls.Grid

    $grid.Children.Add($data_grid) | Out-Null

    $window = New-Object System.Windows.Window -Property @{ Content = $grid }

    $window.ShowDialog() | Out-Null

    $data_grid.SelectedItem
}
1个回答

0

您可以使用Out-GridView命令和-PassThru参数来导出结果或接收作业结果,甚至取消作业。

将结果导出为CSV文件

Get-Job | Out-GridView -PassThru -OutputMode Multiple | Export-Csv "C:\Temp"

删除作业

Get-Job | Out-GridView -PassThru -OutputMode Multiple | Remove-Job

接收作业

Get-Job | Out-GridView -PassThru -OutputMode Single | Receive-Job


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接