User interface 检索powershell中的现有进度条

User interface 检索powershell中的现有进度条,user-interface,powershell,progress-bar,powercli,User Interface,Powershell,Progress Bar,Powercli,我正在powershell中编写一个程序,允许用户在VmWare服务器上创建快照。 一切正常,但当我启动“newsnapshot-Name…”命令时,控制台顶部会出现一个进度条 我想获得进度条并将其放入GUI中 代码如下: function OnApplicationLoad { return $true } function OnApplicationExit { $script:ExitCode = 0 } function Call-Forms_VmWare-Snapsho

我正在powershell中编写一个程序,允许用户在VmWare服务器上创建快照。 一切正常,但当我启动“newsnapshot-Name…”命令时,控制台顶部会出现一个进度条

我想获得进度条并将其放入GUI中

代码如下:

function OnApplicationLoad {
    return $true
}
function OnApplicationExit {
    $script:ExitCode = 0
}
function Call-Forms_VmWare-SnapshotTester {
    [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
    [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
    $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
    $form1 = New-Object System.Windows.Forms.Form
    $groupboxVISServers = New-Object System.Windows.Forms.GroupBox
    $labelVmwvcsa5 = New-Object System.Windows.Forms.Label
    $labelVcenterora1 = New-Object System.Windows.Forms.Label
    $labelvmwvcsa5State = New-Object System.Windows.Forms.Label
    $labelvcenterora1State = New-Object System.Windows.Forms.Label
    $dataGridViewVMList = New-Object System.Windows.Forms.DataGridView
    $dataGridViewCheckBoxColumn = New-Object System.Windows.Forms.DataGridViewCheckBoxColumn
    $dataGridViewServerColumn = New-Object System.Windows.Forms.DataGridViewTextBoxColumn
    $buttonGo = New-Object System.Windows.Forms.Button
    $groupboxState = New-Object System.Windows.Forms.GroupBox
    $labelState = New-Object System.Windows.Forms.Label

    $Form_StateCorrection_Load = {
        $form1.WindowState = $InitialFormWindowState
    }
    $Form_Cleanup_FormClosed = {
        Disconnect-VIServer vmwvcsa5 -Force -Confirm:$false
        Disconnect-VIServer vcenterora1 -Force -Confirm:$false
        try {
            $form1.remove_Load($form1_Load)
            $form1.remove_Load($Form_StateCorrection_Load)
            $form1.remove_FormClosed($Form_Cleanup_FormClosed)
        } catch [Exception] { }
    }
    $form1_Load={
        Write-Host "Chargement du SnapIN..."
        $labelState.Text = "Chargement du SnapIN..."
        if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) {
            Add-PsSnapin VMware.VimAutomation.Core
        }
        Write-Host "Chargement du SnapIN terminé."
        $labelState.Text = "Chargement du SnapIN terminé."
        Write-Host "Tentative de connexion aux VServers..."
        $labelState.Text = "Tentative de connexion aux VServers..."
        Connect-VIServer server1
        If ($?) {
            $labelvmwvcsa5State.Text = "Connecté"
        } Else {
            $labelvmwvcsa5State.Text = "Connexion impossible"
        }
        Connect-VIServer server2
        If ($?) {
            $labelvcenterora1State.Text = "Connecté"
        } Else {
            $labelvcenterora1State.Text = "Connexion impossible"
        }
        Write-Host "Tentative de connexion aux VServers terminées."
        $labelState.Text = "Tentative de connexion aux VServers terminées."
        Write-Host "Récupération des VMs..."
        $labelState.Text = "Récupération des VMs..."
        $flistVM = ".\utils\listeVM.txt"
        $listeVM = (Resolve-Path $flistVM).Path
        $vms = (Get-VM | Sort Name)
        $vms = $vms.Name.ToUpper()
        f_FillDataGridView
        Write-Host "Récupération des VMs terminée."
        $labelState.Text = "Récupération des VMs terminée."
        Write-Host "Programme prêt !"
        $labelState.Text = "Programme prêt !"
    }
    Function f_FillDataGridView {
        ForEach ($Srv in $vms )  {
            $iRow = $dataGridViewVMList.Rows.add()
            $dataGridViewVMList.Rows[$iRow].cells[1].value = $srv
            $dataGridViewVMList.Rows[$iRow].Cells[1].ReadOnly = $true
        }
    }

    $buttonGo_Click={
        $myDate = (Get-Date).ToString('ddMMyyyy')
        ForEach ($row in $dataGridViewVMList.rows) {
            If ($row.cells[0].value -eq $True) {
                Write-Host $row.cells[1].value
                $VM = $row.cells[1].value
                $labelState.Text = "Création de snapshot en cours sur $VM"
                $snapName = "SNAPSHOTTESTER-$myDate"
                New-Snapshot -Name $snapName -Description "Test de création et de suppression de snapshot" -Memory -Quiesce -VM $VM
                If ($?) {
                    $labelState.Text = "Création de snapshot OK sur $VM"
                } Else {
                    $labelState.Text = "Erreur lors de la création de snapshot sur $VM"
                }
                Start-Sleep -Seconds 5

                $snap = Get-Snapshot -Name $snapName -VM $VM
                Remove-Snapshot -Snapshot $snap
                If ($?) {
                    $labelState.Text = "Suppression de snapshot OK sur $VM"
                } Else {
                    $labelState.Text = "Erreur lors de la suppression de snapshot sur $VM"
                }
                $labelState.Text = "Test terminé sur $VM"
                Start-Sleep -Seconds 5
            }
        }
    }

    # form1
    $form1.ClientSize = '300, 400'
    $form1.DataBindings.DefaultDataSourceUpdateMode = 'OnValidation'
    $form1.Name = "form1"
    $form1.Text = "VmWare-SnapshotTester"
    $form1.SizeGripStyle = "Hide"
    $form1.FormBorderStyle = 'Fixed3D'
    $form1.MaximizeBox = $false
    $form1.Controls.Add($groupboxVISServers)
    $form1.Controls.Add($dataGridViewVMList)
    $form1.Controls.Add($buttonGo)
    $form1.Controls.Add($groupboxState)
    $form1.add_Load($form1_Load)
    # groupboxVISServers
    $groupboxVISServers.DataBindings.DefaultDataSourceUpdateMode = 'OnValidation'
    $groupboxVISServers.Location = '12, 12'
    $groupboxVISServers.Name = "groupboxVISServers"
    $groupboxVISServers.Size = '276, 80'
    $groupboxVISServers.Text = "Connexion aux Vservers"
    $groupboxVISServers.Controls.Add($labelVmwvcsa5)
    $groupboxVISServers.Controls.Add($labelVcenterora1)
    $groupboxVISServers.Controls.Add($labelvmwvcsa5State)
    $groupboxVISServers.Controls.Add($labelvcenterora1State)
    # labelVmwvcsa5
    $labelVmwvcsa5.DataBindings.DefaultDataSourceUpdateMode = 'OnValidation'
    $labelVmwvcsa5.Location = '12, 25'
    $labelVmwvcsa5.Name = "labelVmwvcsa5"
    $labelVmwvcsa5.Text = "VmwVCSA5"
    # labelVcenterora1
    $labelVcenterora1.DataBindings.DefaultDataSourceUpdateMode = 'OnValidation'
    $labelVcenterora1.Location = '12, 50'
    $labelVcenterora1.Name = "labelVcenterora1"
    $labelVcenterora1.Text = "VCenterORA1"
    # labelvmwvcsa5State
    $labelvmwvcsa5State.DataBindings.DefaultDataSourceUpdateMode = 'OnValidation'
    $labelvmwvcsa5State.Location = '150, 25'
    $labelvmwvcsa5State.Name = "labelvmwvcsa5State"
    $labelvmwvcsa5State.Text = "Déconnecté"
    # labelvcenterora1State
    $labelvcenterora1State.DataBindings.DefaultDataSourceUpdateMode = 'OnValidation'
    $labelvcenterora1State.Location = '150, 50'
    $labelvcenterora1State.Name = "labelvcenterora1State"
    $labelvcenterora1State.Text = "Déconnecté"
    # dataGridViewVMList
    $dataGridViewVMList.Location = '12, 110'
    $dataGridViewVMList.Size = '276, 200'
    $dataGridViewVMList.RowHeadersVisible = $false
    $dataGridViewVMList.ColumnHeadersVisible = $false
    $dataGridViewVMList.AllowUserToAddRows = $false
    $dataGridViewVMList.AllowUserToResizeColumns = $false
    $dataGridViewVMList.AllowUserToResizeRows = $false
    $dataGridViewVMList.Columns.Add($dataGridViewCheckBoxColumn)
    $dataGridViewVMList.Columns.Add($dataGridViewServerColumn)
    # dataGridViewCheckBoxColumn
    $dataGridViewCheckBoxColumn.Width = 25
    # dataGridViewServerColumn
    $dataGridViewServerColumn.Width = 230
    # buttonGo
    $buttonGo.DataBindings.DefaultDataSourceUpdateMode = 'OnValidation'
    $buttonGo.Location = '12, 330'
    $buttonGo.Size = '276, 23'
    $buttonGo.Name = "buttonGo"
    $buttonGo.Text = "Let's test !"
    $buttonGo.UseVisualStyleBackColor = $True
    $buttonGo.add_Click($buttonGo_Click)
    # groupboxState
    $groupboxState.DataBindings.DefaultDataSourceUpdateMode = 'OnValidation'
    $groupboxState.Location = '12, 360'
    $groupboxState.Name = "groupboxState"
    $groupboxState.Size = '276, 30'
    $groupboxState.Controls.Add($labelState)
    # labelState
    $labelState.DataBindings.DefaultDataSourceUpdateMode = 'OnValidation'
    $labelState.Location = '5, 11'
    $labelState.Size = '270, 15'
    $labelState.Name = "labelState"
    $labelState.Text = "INIT"
    # Init
    $InitialFormWindowState = $form1.WindowState
    $form1.add_Load($Form_StateCorrection_Load)
    $form1.add_FormClosed($Form_Cleanup_FormClosed)
    return $form1.ShowDialog()
}

if((OnApplicationLoad) -eq $true) {
    Call-Forms_VmWare-SnapshotTester | Out-Null
    OnApplicationExit
}

如注释中所述,将
New Snapshot
cmdlet包装在
PowerShell
实例中,您可以在其进度流中侦听
DataAdded
事件:

$buttonGo_Click = {
    <# other stuff going on #>

    # Create PowerShell instance
    $SnapshotPipeline = [powershell]::Create()

    # Add the code
    $SnapshotPipeline.AddScript({
        New-Snapshot -Name $snapName -Description "Test de création et de suppression de snapshot" -Memory -Quiesce -VM $VM
    })

    # Define and register an event handler
    $ProgressHandler = {
        param($s,$e)
        # write progress percent complete value to the LabelState label
        $percentComplete = $s[$e.Index].PercentComplete
        $labelState.Text = "Snapshot $snapName creation: $percentComplete%"
    }
    $SnapshotPipeline.Streams.Progress.add_DataAdded($ProgressHandler)

    # Invoke the New-Snapshot pipeline
    $SnapshotPipeline.Invoke()

    # Unregister event handler
    $SnapshotPipeline.Streams.Progress.remove_DataAdded($ProgressHandler)

    <# other stuff going on #>
}
$buttonGo\u点击={
#创建PowerShell实例
$SnapshotPipeline=[powershell]::Create()
#添加代码
$SnapshotPipeline.AddScript({
新快照-名称$snapName-说明“测试取消确认和取消抑制取消快照”-内存-静止-VM$VM
})
#定义并注册事件处理程序
$ProgressHandler={
参数($s$e)
#将进度完成百分比值写入LabelState标签
$percentComplete=$s[$e.Index].percentComplete
$labelState.Text=“快照$snapName创建:$percentComplete%”
}
$SnapshotPipeline.Streams.Progress.add\u DataAdded($ProgressHandler)
#调用新的快照管道
$SnapshotPipeline.Invoke()
#取消注册事件处理程序
$SnapshotPipeline.Streams.Progress.remove_DataAdded($ProgressHandler)
}

您可以在的实例中包装对
新建快照-名称…
的调用,然后侦听在上引发的事件。给我们看看你的GUI代码。奇怪,但那不起作用。我添加的部分只是没有执行。