使用 powershell 加载组合框中的项目

使用 powershell 加载组合框中的项目

我已将虚拟机加载到我的组合框中

$Form.Add_Loaded({
    Get-VM | ForEach-Object { $WPFcboListVM.Items.Add($_.Name) } ...

当代码实际运行时,两个虚拟机都会启动,而不仅仅是选定的虚拟机。

Add-Type -AssemblyName presentationframework
Add-Type -AssemblyName System.Windows.Forms
$script:pathPanel = Split-Path -parent $MyInvocation.MyCommand.Definition

function LoadXaml ($filename) {
    $XamlLoader=(New-Object System.Xml.XmlDocument)
    $XamlLoader.Load($filename)
    return $XamlLoader
}

$Xaml = LoadXaml($pathPanel+"\frmStartVM.xaml")
$reader = (New-Object System.Xml.XmlNodeReader $Xaml)

try {$Form = [Windows.Markup.XamlReader]::Load($reader)}
catch {Write-Warning "Error: $($Error[0])"; throw}

$Xaml.SelectNodes("//*[@Name]") | ForEach-Object {"trying item $($_.Name)";
    try {Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name) -ErrorAction Stop}
    catch{throw}
}

$Form.Add_Loaded({
    Get-VM | ForEach-Object { $WPFcboListVM.Items.Add($_.Name) }
    $WPFAllVMs.IsChecked = $false
    $WPFbtnStartVMs.IsEnabled = $false
})

$WPFcboListVM.Add_SelectionChanged({
    $WPFbtnStartVMs.IsEnabled = ($WPFcboListVM.SelectedItem -ne $null)
})

$WPFbtnStartVMs.Add_Click({

    $checked = $WPFAllVMs.Add_Checked({ $WPFbtnStartVMs.IsEnabled = $True })
    $unchecked = $WPFAllVMs.Add_UnChecked({ $WPFbtnStartVMs.IsEnabled = $False })

    if ($checked = $True){
        Get-VM | Where-Object {$_.State -eq 'Off'} | Start-VM
    }
    if ($unchecked = $True){
        Get-VM | Where-Object {$_.Name -eq $WPFcboListVM.SelectedItem -and $_.State -eq 'Off'} | Start-VM
    }
    $Form.Close()
})
<Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="StartVMWindow" Height="125" Width="400" WindowStartupLocation="CenterScreen">
    <Grid>
        <ComboBox Name="cboListVM" SelectedItem="" HorizontalAlignment="Left" Margin="104,30,0,0" VerticalAlignment="Top" Width="200" />
        <Label Content="Virtual Machines" HorizontalAlignment="Left" Margin="1,30,0,0" VerticalAlignment="Top"/>
        <Button Name="btnStartVMs" Content="Start VM" IsEnabled="{Binding ElementName=AllVMs, Path=IsChecked}" HorizontalAlignment="Left" Margin="309,30,0,0" VerticalAlignment="Top" Width="75" />
        <CheckBox Name="AllVMs" Content="All" HorizontalAlignment="Left" Margin="44,10,0,0" VerticalAlignment="Top" IsChecked="False"/>

    </Grid>
</Window>

更新

$WPFbtnStartVMs.Add_Click({

    $checked = $WPFAllVMs.Add_Checked({ $WPFbtnStartVMs.IsEnabled = $True })
    $unchecked = $WPFAllVMs.Add_UnChecked({ $WPFbtnStartVMs.IsEnabled = $True })
    if ($unchecked = $True){
        Get-VM | Where-Object {$_.Name -eq $WPFcboListVM.SelectedItem -and $_.State -eq 'Off'} | Start-VM
    }elseif ( $checked = $True ) {
        Get-VM | Where-Object {$_.State -eq 'Off'} | Start-VM
    }
    $Form.Close()
})

相关内容