在 Powershell 中单击 Button 后从 Listbox-Item 获取 ID

Get ID from Listbox-Item after click on Button in Powershell

我生成一个列表框来显示服务器上所有当前的远程会话(用户)

Invoke-Command -ComputerName COMPUTER -credential CREDS -scriptBlock {query.exe user | sort-object }  | %{ [void] $listBox.Items.Add($_) }

我会将此代码段用于我的按钮

$Button= New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Point(10,470)
$Button.Size = New-Object System.Drawing.Size(75,23)
$Button.ForeColor ="red"
$Button.Text = "KILL"
$form.Controls.Add($Button)

最后,我想在单击按钮后选择列表框中的一个项目并获取所选用户的会话 ID。

最后,用户应该点击按钮退出

$Button.Add_Click({ logoff SESSION_OF_MY_LISTED/SELECTED_USER }) ;

单击按钮后如何从列出的(选定用户)获取 ID?

非常感谢!

编辑(完整的列表框片段):

$listBox = New-Object System.Windows.Forms.ListBox 
$listBox.Location = New-Object System.Drawing.Point(10,60) 
$listBox.Size = New-Object System.Drawing.Size(272,20) 
$listBox.Height = 400

Invoke-Command -ComputerName COMPUTER -credential CREDS -scriptBlock {query.exe user | sort-object }  | %{ [void] $listBox.Items.Add($_) }

$form.Controls.Add($listBox)

bad output

例如,您可以通过这种方式实现。我在这里只写相关部分。我没有要连接的服务器,我的计算机上只有一个用户,但它适用于这个用户。也许需要进行一些调整。

# Simple class for using as item for listbox.
class LbItem
{
    LbItem($data)
    {
        # According to your image of bad data, you have different culture,
        # and so different "column names". So you need to change those names here
        # when accessing the elements of $data. My column names in query.exe are:
        #   - USERNAME
        #   - SESSIONNAME
        #   - ID
        #   - STATE
        #   - IDLE TIME
        #   - LOGON TIME

        $this.Id = [System.Convert]::ToInt32($data.ID)
        # It seems, current user has ">" prepended in name, so remove it.
        $this.UserName = $data.USERNAME.TrimStart(">")
        $this.SessionName = $data.SESSIONNAME
        $this.State = $data.STATE
        $this.IdleTime = $data.{IDLE TIME}
        $this.LogonTime = $data.{LOGON TIME}
    }

    [int] $Id
    [string] $UserName
    [string] $SessionName
    [string] $State
    [string] $IdleTime
    [string] $LogonTime

    # This is diplayed in the listbox, so change it for your needs.
    [string] ToString()
    {
        return $this.UserName
    }
}

# Simplified version of your command, because I do not connect to other server,
# but I work only on my own computer.
$data = (query.exe user | Sort-Object) -replace '\s{2,}', ',' | ConvertFrom-Csv

# Fill the listbox with custom classes.
foreach ($dataItem in $data) 
{
    [void] $listBox.Items.Add([LbItem]::new($dataItem))
}

# You can access the Id of current item and use it.
$id = $listBox.SelectedItem.Id