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

如何在PowerShell中获取XAML ComboBox的选中值

获取WPF ComboBox选中值的PowerShell命令

我有如下用于ComboBox的XAML代码,希望在代码中获取其选中的名称值,对应的命令是什么?

#Requires -RunasAdministrator

<Label Content="Remote Server" HorizontalAlignment="Left" Height="31" Margin="76,40,0,0" VerticalAlignment="Top" Width="128"/>
        <ComboBox Name="cboServers" HorizontalAlignment="Left" Height="31" Margin="176,40,0,0" VerticalAlignment="Top" Width="292" IsReadOnly="True">
            <ComboBoxItem Name="S01" Content="Server1" IsSelected="True"/>
            <ComboBoxItem Name="S02" Content="Server2"/>
        </ComboBox>
<ListView Name="listProcesses" HorizontalAlignment="Left" Height="200" Margin="12,107,-140,0" VerticalAlignment="Top" Width="840" IsSynchronizedWithCurrentItem="True" SelectionMode="Single">
           <ListView.View>
                <GridView>
                    <GridViewColumn Header="Process Name" DisplayMemberBinding ="{Binding ProcessID}" Width="100"/>
                    <GridViewColumn Header="ID" DisplayMemberBinding ="{Binding ID}" Width="25"/>
                    <GridViewColumn Header="Username" DisplayMemberBinding ="{Binding Username}" Width="105"/>
                </GridView>
            </ListView.View>

$processes = Invoke-Command -ComputerName $cboServers -scriptBlock { Get-Process Powershell, Pwsh, code -IncludeUserName | format-table Processname, ID, Username } 

$xamlForm.add_Loaded({ $this.Activate()
    $listProcesses.ItemsSource = $processes
 })

更新

获取选中项名称的正确命令是$cboServers.SelectedValue。本次操作目的是从ComboBox获取服务器名称以远程终止进程,完整代码如下:

# Full code to remotely kill a process on a server.
# This is specific to powershell but it's easy to change for any process. 

#Requires -RunasAdministrator

Add-Type -AssemblyName PresentationFramework

[xml] $xaml = @'
<Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:PowershellListView"
        Title="End Processes" Height="450" Width="870">
    <Grid>
        <!-- 
          NOTE THE REQUIRED USE OF IsSynchronizedWithCurrentItem="True" 
          Also, to keep this demo simple, SelectionMode="Single" ensures that only ONE process can be selected at time.
        -->
        <Label Content="Remote Server" HorizontalAlignment="Left" Height="31" Margin="76,40,0,0" VerticalAlignment="Top" Width="128"/>
        <ComboBox Name="cboServers" HorizontalAlignment="Left" Height="31" Margin="176,40,0,0" VerticalAlignment="Top" Width="292" IsReadOnly="True">
        </ComboBox>
           <ListView Name="listProcesses" HorizontalAlignment="Left" Height="200" Margin="12,107,-140,0" VerticalAlignment="Top" Width="840" IsSynchronizedWithCurrentItem="True" SelectionMode="Single">
           <ListView.View>
                <GridView>
                    <GridViewColumn Header="Process Name" DisplayMemberBinding ="{Binding Name}" Width="100"/>
                    <GridViewColumn Header="ID" DisplayMemberBinding ="{Binding ID}" Width="25"/>
                    <GridViewColumn Header="Username" DisplayMemberBinding ="{Binding Username}" Width="255"/>
                </GridView>
            </ListView.View>
        </ListView>
        <Button Name="btnEndProc" Content="Kill Process" HorizontalAlignment="Left" Height="31" Margin="347,347,0,0" VerticalAlignment="Top" Width="144"/>
        <Button Name="btnRefresh" Content="Refresh" HorizontalAlignment="Left" Height="31" Margin="505,40,0,0" VerticalAlignment="Top" Width="84"/>
    </Grid>
</Window>
'@ -replace '^window.*', '<window' -replace 'mc:ignorable="d"', '' -replace "x:N", 'N' -replace 'x:Class="\S+"', ''


    # Parse the XAML and create PowerShell variables named for each control.
    $xmlreader = (New-Object System.Xml.XmlNodeReader $xaml)
    $xamlForm = [Windows.Markup.XamlReader]::Load($xmlReader)
    $xaml.SelectNodes("//*[@Name]") | ForEach-Object -Process {
      Set-variable -name $_.Name -Value $xamlForm.Findname($_.Name)
    }

    [void]$cboServers.items.add("Server1")
    [void]$cboServers.items.add("Server2")
    $cboServers.selectedindex = 0 | out-null
    # write-host ($cboServers.selectedvalue)

    $xamlForm.add_Loaded({ $this.Activate()
    [System.Collections.ArrayList]$processes = Invoke-Command -ComputerName ($cboServers.selectedvalue) -scriptBlock { Get-Process -IncludeUserName | where-object {$_.name -match "Powershell|PWSH"} | select-object name, ID, Username } 
    $listprocesses.ItemsSource = $processes
    $listProcesses.items.Refresh()
    })

$cboServers.add_SelectionChanged({ 


    [System.Collections.ArrayList]$processes = Invoke-Command -ComputerName ($cboServers.selectedvalue) -scriptBlock { Get-Process -IncludeUserName | where-object {$_.name -match "Powershell|PWSH"} | select-object name, ID, Username } 
    $listprocesses.ItemsSource = $processes
    $listProcesses.items.Refresh()
})


$btnEndProc.add_click({
    $selectedProcess = $listProcesses.SelectedItem
    $selectedProcessId = $selectedProcess.Id
    Write-Verbose -Verbose "Forcefully terminating process with ID $selectedProcessId..."
    Invoke-Command -ComputerName ($cboServers.selectedvalue) -scriptBlock { Stop-Process -Force -ID $args[0] } -ArgumentList $selectedProcessId
    # Remove the terminated process from the list view and remove the selection.
    $listProcesses.items.SourceCollection.Remove($selectedProcess)
    $listProcesses.items.Refresh()
    $listProcesses.SelectedIndex = -1
  })

$btnRefresh.add_click({
[System.Collections.ArrayList]$processes = Invoke-Command -ComputerName ($cboServers.selectedvalue) -scriptBlock { Get-Process -IncludeUserName | where-object {$_.name -match "Powershell|PWSH"} | select-object name, ID, Username } 
$listprocesses.ItemsSource = $processes
$listProcesses.items.Refresh()
$listProcesses.SelectedIndex = -1
})
# Enable the button only if a list item is selected.
$listProcesses.add_SelectionChanged({
    $btnEndProc.IsEnabled = $this.SelectedIndex -ne -1
})

# Show the WPF window modally (blocking call).
$null = $xamlForm.ShowDialog()

内容的提问来源于Stack Exchange,提问作者Matt Williamson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:04:55