VMware Cloud Community
GuilhermeAlves
Enthusiast
Enthusiast
Jump to solution

Escaping from Powershell/Cli Form while running a command

I've created a script to find any entity, on any vCenter of my environment. To make  more confort for the users to use the script i've done a GUI too.

The problem is: While the "Get-entities" command is running, the GUI stay freezed.

Is it possible to unfreeze the GUI while running my commands without using Jobs or parallel threads?

1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

How do you try the results with the Receive-Job ?

Do you do something like this

foreach($job in Get-Job){
  Receive-Job -Job $job -OutVariable result

     # Work with the returned results in the variable $result

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

Reply
0 Kudos
8 Replies
LucD
Leadership
Leadership
Jump to solution

Since there is no RunAsync switch on the Get- cmdlets, you could run the line to retrieve the entities with a Start-Job.

You just have to take care to wait till the job finishes and then retrieve the results.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
GuilhermeAlves
Enthusiast
Enthusiast
Jump to solution

Hi Luc,

The problem is that i have to refresh the info in the GUI or in another variables from the possibly Job cmdlets...and can´t retain the output from a Receive-job command...

Let me show you the script..i don't know if you remember but is an evolution of another script i started in another discussion..., However i didn't evolved so much around the Job cmdlets...my bad...

The point of the script is to find an entity from a large environment. Initially, the vCenters are connected and stay connected until the GUI is closed, then all disconnects...

it's quite a mess, i know, but it works fine! i just wanted to unfreeze the GUI =/

<#
==================================================================
Author(s):           Guilherme Alves Stela <guistela@br.ibm.com>
                     Rogerio Regis Pippus <rogerio-regis.pippus@itau-unibanco.com.br>
File:                GugouGUIv4.0.ps1
Date:                13-03-2014
==================================================================
Disclaimer: This script is written as best effort and provides no
warranty expressed or implied. Please contact the author(s) if you
have questions about this script before running or modifying.
==================================================================
.SYNOPSIS
   Pesquisa de entidades no ambiente.
.DESCRIPTION
   Este script pesquisa entidades dos tipos "Host", "Cluster", "Virtual Machine" e "Folder", baseado
   na variável $VCStringlist, que deve conter o caminho de um arquivo que possua uma lista com os nomes
   dos vCenters aos quais o script efetuará logon.
   Para inicializar o Script não é necessário utilizar parâmetros.
   O Script inicializa conectando-se aos vCenters contidos na variável $VCStringlist e, após
   alguns segundos, aguarda ação do usuário.
   As ações disponíveis após iniciado o script são: "Ping", "Pesquisar!", "Limpar tela de output", "Exportar Informações"
   Segue a função de cada ação disponível:
   =>Ping
        Efetua o comando "Test-Connection", que retona o estado de rede do alvo, contido no textbox de input
   =>Pesquisar!
        Pesquisa em todos os vCenters definidos anteriormente, retornando os resultados positivos com o nome, tipo
        e vCenter relativos à entidade procurada.
        => A caixa de seleção "Exibir popup ao encontrar entidades",caso esteja marcada, exibe uma tela de popup e dá
           a opção de parar o script ao encontrar entidades.
   =>Limpar tela de output
        Apaga todas as informações contidas na tela de output
   =>Exportar Informações
        Cria um arquivo de referência para o que estiver apresentando na tela de output.
   =>Ver alarms do ambiente
        Exibe na tela de output todos os alarms ativados do ambiente.
   =>Ver snapshots do ambiente
        Exibe na tela de output todos os snapshots gravados nas VMs do ambiente.
       
.NOTES
  Author:  Guilherme Alves Stela
  Baseado no Script Gugou de Rogerio Regis Pippus (Itaú)
  
.EXAMPLE
   Nenhum exemplo é necessário. Após rodar o ps1, basta utilizar via GUI.
#>

############################################## Start outputThis
function outputThis{
    param($out)
  
   $Form.Refresh()
   $hour =   (get-date).hour
   $minute = (get-date).minute
   $second = (get-date).second 
   $activeuser = whoami
  
   $timestamp = "["+$activeuser+"] "+$hour+"h"+$minute+"m"+$second+"s =========================================================== `n" | Out-String
   $Form.Refresh()
  
   if( $outputBox){
        $outputBox.text  = ($timestamp +"`t"+ $out| Out-String)+ $outputBox.text
        $Form.Refresh()
   }   
}
############################################## end outputThis

############################################## start function Loading
function Loading{
    $total = 100;
    $step = 100/$total;
    $size = 0;
    for($i = 0; $i -lt $total; $i++){
        $sizeF = "{0:N0}" -f $size;
        $size +=$step;
        sleep -Milliseconds 10;
        if($i -eq 0){
            write-progress -activity "Aguarde" -status "Carregando..." -percentcomplete 1;
        }if($size -ge 95){
            write-progress -activity "Aguarde" -status "Carregando..." -percentcomplete 100;
            sleep -Milliseconds 100;
            $size =0;
            $i=0;}
        elseif(($i*$step) -lt 100){
            write-progress -activity "Aguarde" -status "Carregando..." -percentcomplete ($i*$step);
        }
    }
};
############################################## end function Loading

############################################## Adding PowerCLI Snapin
if(!(get-pssnapin | where {$_.name -eq "vmware.vimautomation.core"})) {
        try {
           add-pssnapin VMware.VimAutomation.Core
        } catch {
            $ErrorMessage = $_.Exception.Message
            outputThis "$ErrorMessage"
        }
}
######################################################

######################################################Set to multiple VC Mode
try{
if(((Get-PowerCLIConfiguration -Scope Session).DefaultVIServerMode) -ne "Multiple") {
   Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Scope AllUsers -Confirm:$false
   Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Scope User -Confirm:$false
   Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Scope Session -Confirm:$false
}}catch{
      $ErrorMessage = $_.Exception.Message
      outputThis "$ErrorMessage"
}
######################################################

############################################## start connectvCenters
function connectvCenters{
    param($list)
$Form.Refresh()
$arrayConnectedVC =@()

      foreach($itemList in $list){
           $Form.Refresh()
            try{
                $sessionID = $global:defaultviservers | where {$_.Name -eq $itemList} |Select -First 1 -ExpandProperty SessionId
               
                if($sessionId){
           $vc = Connect-VIServer -server $itemList -Session $sessionId -wa 0
                    outputThis "Reconectado ao servidor '$vc'"
                    $Form.Refresh()
                    #Write-Host "Reconectado ao servidor '$vc'"
                    $arrayConnectedVC += $vc
                    
          }else{
                    $vc = Connect-VIServer -server $itemList -wa 0
                    outputThis "Conectado ao servidor '$vc'"
                    $Form.Refresh()
                    #Write-Host "Conectado ao servidor '$vc'"
                    $arrayConnectedVC += $vc
                }
            }catch{
            $ErrorMessage = $_.Exception.Message
                outputThis "Não foi possível conectar ao servidor '$vc' `n  $ErrorMessage"
               
                $Form.Refresh()
            }
           
       }
    return $arrayConnectedVC
}
############################################## end connectvCenters    

##############################################start Dotheseactions
function DotheseActions{

$result = Validate-IsEmptyTrim $textBox.Text   

    if($result -eq $true){
        [System.Windows.Forms.MessageBox]::Show(“Antes de iniciar a pesquisa, digite algo na caixa de texto“,"Gugou v4.0","OK","Warning")
        $textbox.BackColor = "Red"
        $textbox.ForeColor = "white"
                                              
    }else{
        $textbox.BackColor = "LightGreen"
        $textbox.ForeColor = "Black"
       
        if($Radiobutton7.checked){
            #inicia pesquisa por Todas as entidades
            FindALL
        }elseif($Radiobutton6.checked){
            #inicia pesquisa por cluster
            FindCluster
        }elseif($Radiobutton5.checked){
            #inicia pesquisa por host
            FindHost
        }elseif($Radiobutton4.checked){
            #inicia pesquisa por VM
            FindVM
        }
    }
}
##############################################end dotheseactions

############################################## start Valemptytrim
function Validate-IsEmptyTrim ([string] $field)
{
    if($field -eq $null -or $field.Trim().Length -eq 0)
    {
        return $true   
    }
   
    return $false
}
############################################## end Valemptytrim

############################################## Start pingInfo
function pingInfo {
$result = Validate-IsEmptyTrim $textBox.Text   

    if($result -eq $true){
        [System.Windows.Forms.MessageBox]::Show(“Antes de iniciar a pesquisa, digite algo na caixa de texto“,"Gugou v4.0","OK","Warning")
        $textbox.BackColor = "Red"
         $textbox.ForeColor = "white"                    
    }else{
       
         $textbox.BackColor = "LightGreen"
         $textbox.ForeColor = "Black"

if ($RadioButton1.Checked -eq $true) {$nrOfPings=1}
if ($RadioButton3.Checked -eq $true) {$nrOfPings=3}

$computer= $TextBox.text;

    try{
        $pingresult = test-connection -computername $computer -count $nrOfPings -ea Stop | select Address,IPV4Address,ReplySize,ResponseTime| Out-String
        outputThis "$pingresult"
        return 1
    }catch{
         $ErrorMessage = $_.Exception.Message
        outputThis "$ErrorMessage"  
        $textbox.BackColor = "Red"
        $textbox.ForeColor = "white"
        return 0
   }
  } 
}
############################################## end pingInfo

############################################## Start Triggered Alarms
Function Get-TriggeredAlarms {
param (
  $vc = $(throw "A vCenter must be specified."),
  [System.Management.Automation.PSCredential]$credential
)
    <#
    .SYNOPSIS
        Get Multiple vCenter Alarms and shows
    .DESCRIPTION
        Get Multiple vCenter Alarms and shows
    .NOTES
        Author:  Guilherme Alves Stela
        Based on http://wannemacher.us/?p=457
    .PARAMETER Vcenter
        Gives to the script the Vcenter name to connect.
    .EXAMPLE
        Get-TriggeredAlarms "MyvCenter"
    #>
  if (!$vc) {
  Write-Host "Failure connecting to the vCenter $vCenter."
  exit
}
$rootFolder = Get-Folder -Server $vc "Datacenters"

foreach ($ta in $rootFolder.ExtensionData.TriggeredAlarmState) {
   
     $alarm = "" | Select-Object VC, EntityType, Alarm, Entity, Status, Time,AckBy,AckTime
  $alarm.VC = $vC
  $alarm.Alarm = (Get-View -Server $vc $ta.Alarm).Info.Name
   $entity = Get-View -Server $vc $ta.Entity
  $alarm.Entity = $entity.Name
  $alarm.EntityType = $entity.GetType().Name
  $alarm.Status = $ta.OverallStatus
  $alarm.Time = $ta.Time
  #$alarm.Acknowledged = $ta.Acknowledged
  $alarm.AckBy = $ta.AcknowledgedByUser
  $alarm.AckTime = $ta.AcknowledgedTime
        
        if(($alarm.Alarm -ne "Virtual machine cpu usage") -and ($alarm.Alarm -ne "Virtual machine memory usage")){
        $alarm
        }
    }
}
############################################## End Triggered Alarms


############################################## Start Snapshots
Function Get-Snapshots {
param (
  $vc = $(throw "A vCenter must be specified."),
  [System.Management.Automation.PSCredential]$credential
)
    <#
    .SYNOPSIS
        Get Multiple vCenter Snapshots and shows
    .DESCRIPTION
        Get Multiple vCenter Snapshots and shows
    .NOTES
        Author:  Guilherme Alves Stela
        Based on http://wannemacher.us/?p=457
    .PARAMETER Vcenter
        Gives to the script the Vcenter name to connect.
    .EXAMPLE
        Get-Snapshots "MyvCenter"
    #>
  if (!$vc) {
  Write-Host "Failure connecting to the vCenter $vCenter."
  exit
}
     $GetSnaps = Get-VM -server $vc

    $myVMs = Get-VM -Server $vc
    $VMsWithSnaps = @()
    $count = 0
    foreach ($vm in $myVMs) {
        $vmView = $vm | Get-View
       
        if ($vmView.snapshot -ne $null) {
            Write-Host "VM $vm tem snapshots"
            $SnapshotEvents = Get-VIEvent -Entity $vm -type info -MaxSamples 1000 | Where {
            $_.FullFormattedMessage.contains("Create virtual machine snapshot")}
            try {
                $user = $SnapshotEvents[0].UserName
                $time = $SnapshotEvents[0].CreatedTime
            }catch [System.Exception] {
                $user = $SnapshotEvents.UserName
                $time = $SnapshotEvents.CreatedTime
            }
            $VMInfo = “” | Select "VM","Snapshot Name","Snapshot Description","CreationDate","User"
            $VMInfo."VM" = $vm.Name
            $VMInfo."CreationDate" = $time
            $VMInfo."User" = $user
            $VMInfo."Snapshot Name" = $vmView.snapshot.rootsnapshotlist.Name
            $VMInfo."Snapshot Description" = $vmView.snapshot.rootsnapshotlist.Description
            $VMsWithSnaps
            $count+1
        }
    }

    outputThis "$count Snapshots Encontrados"
}
############################################## End Snapshots

############################################## startFindALL
function FindALL{
        $countALL = 0
        $outputALL =@()
        outputThis  "******************** Iniciando pesquisa por todas as Entidades ********************"
    ##startforeach vcs
    foreach($vc in $conns){
         
            $Form.Refresh()  
            $inv =@()
            $count = 0
            $output = ""
            ###nome da entidade procurada
            $typed = $textBox.text
            outputThis "Procurando por $typed em $vc..."
            $inv = Get-Inventory -Location (get-datacenter -Server $vc)
             
            foreach($invITEM in $inv) {
                try{             
                    $compare = ($invITEM|select Name).Name -like "$typed*"
                }catch{
                    outputThis "Não é possível executar esta procura. #Undefined"               
                    #Write-host "Não é possível executar esta procura. #Undefined"               
                    #chamar função Start
                    Break   
                }   
                if($compare){
                           
                    $name = ($invITEM|select Name).Name
                    $type = $invITEM.Id.Split("-")[0]
                    $VCserver = ($invITEM.Uid.Split("@")[1]).Split(":")[0]           
                    $output = "" | Select-Object Name, Type, Vcenter  
                    $output.Name = $name
                    $output.Type = $type
                    $output.Vcenter = $VCserver
                               
                    if($outputALL -notcontains $output){
                        $count = $count +1
                        $countALL = $countALL +1   
                        $outputALL +=$output    
                    }           
                }
            $output = ""
            }#end foreach $inv
            if($outputALL){
              $lengthOutput = $outputALL.length
              outputThis ("$lengthOutput Entidades encontradas: "+(($outputALL|%{$_|Select-Object Name, Type, Vcenter})|ft -autosize|out-string))
       
              if($chkbox.checked -eq $true){
                $a = new-object -comobject wscript.shell
                $intAnswer = $a.popup("Entidades Encontradas: `n "+(($outputALL|%{$_|Select-Object Name, Type, Vcenter})|ft|out-string)+" `n Continuar procurando?",0,"Gugou v4.0",4)
                $outputALL = @()
                If ($intAnswer -eq 6) {
                    #$a.popup("You answered yes.")
                    #do nothing
                }else {
                    #$a.popup("You answered no.") 
                    Break
                }
              }
              $Form.Refresh()
              $outputALL = @()
                      
            }else{
              $Form.Refresh()
               $outputALL = @()
            }
     }#end foreach vcs
     $Form.Refresh()
     outputThis ("Fim da pesquisa.")
}
############################################## End FindALL

############################################## startFindHost
function FindHost{
        $countALL = 0
        $outputALL =@()
          $Form.Refresh()
        outputThis  "******************** Iniciando pesquisa por Host ********************"
          $Form.Refresh()
    ##startforeach vcs
    foreach($vc in $conns){
         
          $Form.Refresh()  
            $inv =@()
            $count = 0
            $output = ""
           
            ###nome da entidade procurada
            $typed = $textBox.text
            $Form.Refresh()
            outputThis "Procurando por $typed em $vc..."
              $Form.Refresh()
            $inv = Get-VMHost -Location (get-datacenter -Server $vc)
             
            foreach($invITEM in $inv) {
                try{             
                    $compare = ($invITEM|select Name).Name -like "$typed*"
                }catch{
                  $Form.Refresh()
                    outputThis "Não é possível executar esta procura. #Undefined"               
                      $Form.Refresh()
                    #Write-host "Não é possível executar esta procura. #Undefined"               
                    #chamar função Start
                    Break   
                }   
                if($compare){
                                                     
                    $name = ($invITEM|select Name).Name
                    $type = $invITEM.Id.Split("-")[0]
                    $VCserver = ($invITEM.Uid.Split("@")[1]).Split(":")[0]           
                    $output = "" | Select-Object Vcenter, Name,PowerState,ConnectionState,NumCpu,MemoryTotalGB,Manufacturer,Model,Version
                    $output.Name = $invITEM.Name
                    $output.PowerState = $invITEM.PowerState
                    $output.Vcenter = $VCserver
                    $output.ConnectionState = $invITEM.ConnectionState
                    $output.NumCpu = $invITEM.NumCpu
                    $output.MemoryTotalGB = $invITEM.MemoryTotalGB
                    $output.Manufacturer = $invITEM.Manufacturer
                    $output.Model = $invITEM.Model
                    $output.Version = $invITEM.Version

                    if($outputALL -notcontains $output){
                        $count = $count +1
                        $countALL = $countALL +1   
                        $outputALL +=$output    
                    }           
                }
            $output = ""
            }#end foreach $inv
            if($outputALL){
              $lengthOutput = $outputALL.length
                $Form.Refresh()
              outputThis ("$lengthOutput Entidades encontradas: "+(($outputALL|%{$_|Select-Object Vcenter, Name,PowerState,ConnectionState,NumCpu,MemoryTotalGB,Manufacturer,Model,Version })|out-string))
          $Form.Refresh()
              if($chkbox.checked -eq $true){
                $a = new-object -comobject wscript.shell
                $intAnswer = $a.popup("Entidades Encontradas: `n "+(($outputALL|%{$_|Select-Object Vcenter, Name})|fl|out-string)+" `n Continuar procurando?",0,"Gugou v4.0",4)
                $outputALL = @()
                If ($intAnswer -eq 6) {
                    #$a.popup("You answered yes.")
                    #do nothing
                }else {
                    #$a.popup("You answered no.") 
                    Break
                }
              }
              $Form.Refresh()
              $outputALL = @()
                      
            }else{
             $Form.Refresh()
               $outputALL = @()
            }
     }#end foreach vcs
     $Form.Refresh()
     outputThis ("Fim da pesquisa.")
       $Form.Refresh()
}
############################################## End FindHost

############################################## Start FindVM
function FindVM{
        $countALL = 0
        $outputALL =@()
          $Form.Refresh()
        outputThis  "******************** Iniciando pesquisa por VM ********************"
          $Form.Refresh()
    ##startforeach vcs
    foreach($vc in $conns){
         
           $Form.Refresh()   
            $inv =@()
            $count = 0
           
            ###nome da entidade procurada
            $typed = $textBox.text
          $Form.Refresh()
            outputThis  "Procurando por $typed em $vc..."
              $Form.Refresh()
            $inv = Get-VM -Server $vc
             
            foreach($invITEM in $inv) {
                try{             
                    $compare = ($invITEM|select Name).Name -like "$typed*"
                }catch{   $Form.Refresh()
                    outputThis  "Não é possível executar esta procura. #Undefined"               
                      $Form.Refresh()
                    #Write-host "Não é possível executar esta procura. #Undefined"               
                    #chamar função Start
                    Break   
                }   
                if($compare){
                                                     
                    $name = ($invITEM|select Name).Name
                    $type = $invITEM.Id.Split("-")[0]
                    $VCserver = ($invITEM.Uid.Split("@")[1]).Split(":")[0]           
                    $output = "" | Select-Object Vcenter,Name,PowerState,NumCpu,MemoryGB,Version,Notes,Host,Folder,isTemplate
                    $output.Vcenter = $VCserver
                    $output.Name = $invITEM.Name
                    $output.PowerState = $invITEM.PowerState
                    $output.NumCpu = $invITEM.NumCpu
                    $output.MemoryGB = $invITEM.MemoryGB
                    $output.Version = $invITEM.Version
                    $output.Notes = $invITEM.Notes
                    $output.Host = $invITEM.VMHost
                    $output.Folder = $invITEM.Folder
                    $output.isTemplate = $invITEM.extensiondata.Config.Template
                   
                    if($outputALL -notcontains $output){
                        $count = $count +1
                        $countALL = $countALL +1   
                        $outputALL +=$output    
                    }           
                }
            $output = ""
            }#end foreach $inv
            if($outputALL){
              $lengthOutput = $outputALL.length
                $Form.Refresh()
              outputThis  ("$lengthOutput Entidades encontradas: "+(($outputALL|%{$_|Select-Object Vcenter,Name,PowerState,NumCpu,MemoryGB,Version,Notes,Host,Folder,isTemplate })|out-string))
                $Form.Refresh()
       
              if($chkbox.checked -eq $true){
                $a = new-object -comobject wscript.shell
                $intAnswer = $a.popup("Entidades Encontradas: `n "+(($outputALL|%{$_|Select-Object Vcenter,Name})|fl|out-string)+" `n Continuar procurando?",0,"Gugou v4.0",4)
                $outputALL = @()
                If ($intAnswer -eq 6) {
                    #$a.popup("You answered yes.")
                    #do nothing
                }else {
                    #$a.popup("You answered no.") 
                    Break
                }
              }
              $Form.Refresh()
              $outputALL = @()
                      
            }else{
               $Form.Refresh()
               $outputALL = @()
            }
     }#end foreach vcs
   $Form.Refresh()
     outputThis ("Fim da pesquisa.")
       $Form.Refresh()
}
############################################## End FindVM

############################################## Start FindCluster
function FindCluster{
        $countALL = 0
        $outputALL =@()
    ##startforeach vcs
    outputThis  "******************** Iniciando pesquisa por Cluster ********************"
    foreach($vc in $conns){
         
            $Form.Refresh()  
            $inv =@()
            $count = 0
           
            ###nome da entidade procurada
            $typed = $textBox.text
              $Form.Refresh() 
            outputThis  "Procurando por $typed em $vc..."
            $inv = Get-Cluster -Server $vc
              $Form.Refresh() 
            foreach($invITEM in $inv) {
                try{             
                    $compare = ($invITEM|select Name).Name -like "$typed*"
                }catch{
                  $Form.Refresh()
                    outputThis  "Não é possível executar esta procura. #Undefined"               
                      $Form.Refresh()
                    #Write-host "Não é possível executar esta procura. #Undefined"               
                    #chamar função Start
                    Break   
                }   
                if($compare){
                                                     
                    $name = ($invITEM|select Name).Name
                    $type = $invITEM.Id.Split("-")[0]
                    $VCserver = ($invITEM.Uid.Split("@")[1]).Split(":")[0]           
                    $output = "" | Select-Object Vcenter,Name,HAEnabled,HAFailoverLevel,DrsEnabled,DrsAutomationLevel
                    $output.Vcenter = $VCserver
                    $output.Name = $invITEM.Name
                    $output.HAEnabled = $invITEM.HAEnabled
                    $output.HAFailoverLevel = $invITEM.HAFailoverLevel
                    $output.DrsEnabled = $invITEM.DrsEnabled
                    $output.DrsAutomationLevel = $invITEM.DrsAutomationLevel 
                   
                    if($outputALL -notcontains $output){
                        $count = $count +1
                        $countALL = $countALL +1   
                        $outputALL +=$output    
                    }           
                }
            $output = ""
            }#end foreach $inv
            if($outputALL){
              $lengthOutput = $outputALL.length
                $Form.Refresh()
              outputThis  ("$lengthOutput Entidade(s) encontrada(s): "+(($outputALL|%{$_|Select-Object Vcenter,Name,HAEnabled,HAFailoverLevel,DrsEnabled,DrsAutomationLevel })|out-string))
                $Form.Refresh()
              if($chkbox.checked -eq $true){
                $a = new-object -comobject wscript.shell
                $intAnswer = $a.popup("Entidades Encontradas: `n "+(($outputALL|%{$_|Select-Object Vcenter,Name})|fl|out-string)+" `n Continuar procurando?",0,"Gugou v4.0",4)
                $outputALL = @()
                If ($intAnswer -eq 6) {
                    #do nothing
                }else {
                    Break
                }
              }
              $Form.Refresh()
              $outputALL = @()
                      
            }else{
               $Form.Refresh()
               $outputALL = @()
            }
     }#end foreach vcs
    $Form.Refresh()
     outputThis ("Fim da pesquisa.")
}
####################################################### end FindCluster

################################################ Start Form Creation
function OnFormClosing_MenuForm($Sender,$e){
    # $this represent sender (object)
    # $_ represent  e (eventarg)
       $Form.Refresh()
        $a = new-object -comobject wscript.shell
        $Form.Refresh()
       
        $intAnswer = $a.popup("Tem certeza que deseja sair?",0,"Gugou v4.0",4100)
        $Form.Refresh()
       
        If ($intAnswer -eq 6) {
                                               
                        outputThis "Desconectando vCenters..."
                        $Form.Refresh()
                        try{
                            Disconnect-VIServer * -wa 0 -ea 0 -Force -Confirm:$false
                            $Form.Refresh()
                            outputThis "vCenters Desconectados! Encerrando script..."
                            $Form.Refresh()
                       
                            $Form.Refresh()
                        }catch{
                            outputThis "Não há vCenters conectados, encerrando script..."
                            $Form.Refresh()
                          
                        } 
                        # Allow closing 
                        $Form.Refresh() 
                              
                        ($_).Cancel= $false
                                         
         }else {
                # Don´t Allow closing              
                $Form.Refresh()
                        
                ($_).Cancel= $true
                }    
}

function GenerateForm{

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
[System.Windows.Forms.Application]::EnableVisualStyles()
#
#gerar o Form
#
$Form = New-Object System.Windows.Forms.Form   
$Form.Size = New-Object System.Drawing.Size(785,460) 
#$Form.MinimumSize = New-Object System.Drawing.Size(785,460)

$Form.StartPosition = "CenterScreen"
try{
    $Icon = New-Object system.drawing.icon ("my icon from file...") -ea Stop
}catch{
    Write-Host "Não foi possível carregar o ícone."
    outputThis "Não foi possível carregar o ícone."
}
$Form.Icon = $Icon
$Form.MinimizeBox = $True
$Form.MaximizeBox = $True

$Form.SizeGripStyle= "Hide"
$Form.WindowState = "Normal"
#$Form.FormBorderStyle="FixedDialog"
$Form.Text = "Gugou v5.0 @ Itaú Virtualização"
$Form.Opacity = 0.97
$Form.ControlBox = $true
$Form.Add_FormClosing( {OnFormClosing_MenuForm $Form $EventArgs} )


############################################## Start Form toolstrips
$MS_Main = new-object System.Windows.Forms.MenuStrip
$fileToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$exitToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$editionToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$HelpToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$aboutToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$TriggAlarmsToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$SnapToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
#
# MS_Main
#
$MS_Main.Items.AddRange(@($fileToolStripMenuItem,$editionToolStripMenuItem,$helpToolStripMenuItem))
#$MS_Main.Items.AddRange(@($fileToolStripMenuItem))
$MS_Main.Location = new-object System.Drawing.Point(0, 0)
$MS_Main.Name = "MS_Main"
$MS_Main.Size = new-object System.Drawing.Size(354, 24)
$MS_Main.TabIndex = 0
$MS_Main.Text = "menuStrip1"
$MS_Main.BackColor = "lightblue"
#
# fileToolStripMenuItem
#
$fileToolStripMenuItem.DropDownItems.AddRange(@($TriggAlarmsToolStripMenuItem))
$fileToolStripMenuItem.DropDownItems.AddRange(@($SnapToolStripMenuItem))
$fileToolStripMenuItem.DropDownItems.AddRange(@($exitToolStripMenuItem))
$fileToolStripMenuItem.Name = "fileToolStripMenuItem"
$fileToolStripMenuItem.Size = new-object System.Drawing.Size(35, 20)
$fileToolStripMenuItem.Text = "&Arquivo"
#
# exitToolStripMenuItem
#
$exitToolStripMenuItem.Name = "openToolStripMenuItem"
$exitToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$exitToolStripMenuItem.Text = "&Sair"
$exitToolStripMenuItem.Add_Click( { $Form.Close()} )#
# TriggAlarmsToolStripMenuItem
#
$TriggAlarmsToolStripMenuItem.Name = "TriggAlarmsToolStripMenuItem"
$TriggAlarmsToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$TriggAlarmsToolStripMenuItem.Text = "&Ver Alarms do Ambiente"
$TriggAlarmsToolStripMenuItem.Add_Click( {outputThis "Aguarde enquanto trago os alarms...";$Form.Refresh(); outputThis ($conns |%{Get-TriggeredAlarms ($_)}|fl| Out-String)} )
# TriggAlarmsToolStripMenuItem
#
$SnapToolStripMenuItem.Name = "SnapToolStripMenuItem"
$SnapToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$SnapToolStripMenuItem.Text = "&Ver Snapshots do Ambiente"
$SnapToolStripMenuItem.Add_Click( {outputThis "Estamos trabalhando nisso...";$Form.Refresh();}) #outputThis ($conns |%{Get-Snapshots ($_)}|fl| Out-String)} )
#
# editToolStripMenuItem
#
$editionToolStripMenuItem.Name = "editionToolStripMenuItem"
$editionToolStripMenuItem.Size = new-object System.Drawing.Size(35, 20)
$editionToolStripMenuItem.Text = "&Editar"
#
# HelpToolStripMenuItem
#
$helpToolStripMenuItem.DropDownItems.AddRange(@($aboutToolStripMenuItem))
$helpToolStripMenuItem.Name = "helpToolStripMenuItem"
$helpToolStripMenuItem.Size = new-object System.Drawing.Size(35, 20)
$helpToolStripMenuItem.Text = "&Ajuda"
#
# aboutToolStripMenuItem
#
$aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"
$aboutToolStripMenuItem.Size = new-object System.Drawing.Size(35, 20)
$aboutToolStripMenuItem.Text = "&Sobre..."
$aboutToolStripMenuItem.Add_Click( {
#
#About Form...
#
$Form2 = New-Object system.Windows.Forms.Form
$Form2.Text = ""

$Form2.BackgroundImageLayout = "None"
$Form2.WindowState = "Normal"
$Form2.FormBorderStyle="FixedDialog"
$Form2.StartPosition = "CenterScreen"
$Form2.Size = new-object System.Drawing.Size(400,200)

$Label2 = New-Object System.Windows.Forms.Label
$Label2.Text = "Desenvolvido por `n Guilherme Alves Stela - IBM `n Rogério Regis Pippus - Itaú `n Versão 5.0 @2014"
$Label2.BackColor = "Transparent"
$Label2.Size = New-Object System.Drawing.Size(300,50)
$Label2.Location = New-Object System.Drawing.Size(150,15)
$Form2.Controls.Add($Label2)

$Button0 = New-Object System.Windows.Forms.Button
$Button0.Location = New-Object System.Drawing.Size(340,140)
$Button0.Size = New-Object System.Drawing.Size(40,20)
$Button0.Text = "OK"
$Button0.Add_Click({$Form2.Close()})
$Form2.Controls.Add($Button0)
$Form2.ShowDialog()
} )
$Form.Controls.Add($MS_Main)
$Form.MainMenuStrip = $MS_Main
############################################## end Form toolstrips

############################################## groupbox1
$groupbox1 = New-Object System.Windows.Forms.groupbox
$groupbox1.Text = "O que você procura?"
$groupbox1.Size = New-Object System.Drawing.Size(360,87)
$groupbox1.Location = New-Object System.Drawing.Size(15,40)

$Form.Controls.Add($groupbox1)
#
# Ping groupbox
#
$groupbox2 = New-Object System.Windows.Forms.groupbox
$groupbox2.Text = "Ping"
$groupbox2.Size = New-Object System.Drawing.Size(130,68)
$groupbox2.Location = New-Object System.Drawing.Size(220,10)
$groupbox1.Controls.Add($groupbox2)
############################################## end groupbox1

############################################## Start radio buttons
$RadioButton1 = New-Object System.Windows.Forms.RadioButton
$RadioButton1.Location = new-object System.Drawing.Point(10,15)
$RadioButton1.size = New-Object System.Drawing.Size(60,20)
$RadioButton1.Checked = $true
$RadioButton1.Text = "1 Ping"
$groupBox2.Controls.Add($RadioButton1)

$RadioButton3 = New-Object System.Windows.Forms.RadioButton
$RadioButton3.Location = new-object System.Drawing.Point(10,40)
$RadioButton3.size = New-Object System.Drawing.Size(60,20)
$RadioButton3.Text = "3 Pings"
$groupBox2.Controls.Add($RadioButton3)

$RadioButton4 = New-Object System.Windows.Forms.RadioButton
$RadioButton4.Location = new-object System.Drawing.Point(155,10)
$RadioButton4.size = New-Object System.Drawing.Size(60,20)
$RadioButton4.Text = "VM"
$groupBox1.Controls.Add($RadioButton4)

$RadioButton5 = New-Object System.Windows.Forms.RadioButton
$RadioButton5.Location = new-object System.Drawing.Point(155,28)
$RadioButton5.size = New-Object System.Drawing.Size(60,20)
$RadioButton5.Text = "Host"
$groupBox1.Controls.Add($RadioButton5)

$RadioButton6 = New-Object System.Windows.Forms.RadioButton
$RadioButton6.Location = new-object System.Drawing.Point(155,46)
$RadioButton6.size = New-Object System.Drawing.Size(60,20)
$RadioButton6.Text = "Cluster"
$groupBox1.Controls.Add($RadioButton6)

$RadioButton7 = New-Object System.Windows.Forms.RadioButton
$RadioButton7.Location = new-object System.Drawing.Point(155,64)
$RadioButton7.size = New-Object System.Drawing.Size(60,20)
$RadioButton7.Text = "?"
$groupBox1.Controls.Add($RadioButton7)
$RadioButton7.Checked = $true

############################################## end radio buttons

############################################## start checkbox
$chkbox = New-Object System.Windows.Forms.CheckBox
$chkbox.Location = New-Object System.Drawing.Size(15,132)
$chkbox.Size = New-Object System.Drawing.Size(220,20)
$chkbox.Text = "Exibir popup ao encontrar entidades."
$chkbox.checked = $true
$Form.Controls.Add($chkbox)
############################################## end checkbox

############################################## Start Text boxes
#
# input text box
#
function handler_textBox_KeyPress{

           $textbox.BackColor = "white"
           $textbox.ForeColor = "black"
    If ($_.KeyChar -eq 13){
        DotheseActions
    }
}
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Size(15,20)
$textBox.Size = New-Object System.Drawing.Size(130,20)
$textBox.add_KeyPress({handler_textBox_KeyPress})
$groupbox1.Controls.Add($textBox)
#
# output text box
#
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(14,150)
$outputBox.Size = New-Object System.Drawing.Size(750,240)
$outputBox.MultiLine = $True
$outputBox.BackColor = "black"
$outputBox.ForeColor = "lightblue"
$outputBox.Readonly = $true
$outputBox.ScrollBars = "Vertical"
$outputBox.Font = "Arial,9"
$outputBox.Wordwrap = $false
$OutputBox.ScrollBars = [System.Windows.Forms.ScrollBars]::Both
$OutputBox.Anchor = "Top,Bottom,Left,Right"
$Form.Controls.Add($outputBox)
############################################## end text fields

############################################## Start buttons
#
# Clear output button
#
$ClearButton = New-Object System.Windows.Forms.Button
$ClearButton.Anchor = "Bottom,Left"
$ClearButton.Location = New-Object System.Drawing.Size(15,395)
$ClearButton.Size = New-Object System.Drawing.Size(150,20)
$ClearButton.FlatAppearance.MouseOverBackColor = [System.Drawing.Color]::FromArgb(255, 255, 192); 
$ClearButton.FlatStyle = [System.Windows.Forms.FlatStyle]::Flat
$ClearButton.Text = "Limpar tela de Output"
$ClearButton.Add_Click({$outputBox.Text = "";outputThis "Aguardando comando...";})
$Form.Controls.Add($ClearButton)
#
# Search button
#
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(15,45)
$Button.Size = New-Object System.Drawing.Size(130,25)
$Button.Text = "Procurar!"
$Button.Add_Click({DotheseActions})
$groupbox1.Controls.Add($Button)
#
# Ping button
#
$ButtonPing = New-Object System.Windows.Forms.Button
$ButtonPing.Location = New-Object System.Drawing.Size(75,13) 
$ButtonPing.Size = New-Object System.Drawing.Size(45,50)
$ButtonPing.Text = "Ping!"
$ButtonPing.Add_Click({pingInfo})
$groupbox2.Controls.Add($ButtonPing)
#
# Export output to file button
#
$exportButton = New-Object System.Windows.Forms.Button
$exportButton.Anchor = "Bottom,Left"
$exportButton.Location = New-Object System.Drawing.Size(180,395)
$exportButton.Size = New-Object System.Drawing.Size(150,20)
$exportButton.FlatAppearance.MouseOverBackColor = [System.Drawing.Color]::FromArgb(255, 255, 192); 
$exportButton.FlatStyle = [System.Windows.Forms.FlatStyle]::Flat
$exportButton.Text = "Exportar Informações"
$exportButton.Add_Click({
    $app = new-object -com Shell.Application
    $Form.Topmost = $False
    $folder = $app.BrowseForFolder(0, "Select Folder", 0, "Desktop")
    $result = Validate-IsEmptyTrim $folder  
    if($result -eq $true){    
       outputThis "Erro ao exportar informações. Necessário informar caminho para salvar o arquivo."
    }else{
        $dataTD = get-date
        $dd = $dataTD.Day
        $mm =$dataTD.Month
        $yy = $dataTD.Year
        $hh = $dataTD.Hour
        $mmm = $dataTD.Minute
        $ss = $dataTD.Second

        $TDformatted = "$dd-$mm-$yy $hh"+"h"+"$mmm"+"m$ss"+"s"  
     $path = $folder.Self.Path+"\ExportInfo$TDformatted.log"   
       
        $outputBox.Text | Set-Content -Path $path
        outputThis "Infomações exportadas com êxito no caminho: $path"
    }    
})
$Form.Controls.Add($exportButton)
############################################## end buttons
#
#End Form Creation
#
#Enabling Form ===>
#
$form.Add_Shown( { $form.Activate() } )
$Form.Visible = $true
$Form.Refresh()
try{
    $VCStringlist = get-content "my vcenters from a file or list" -ErrorAction Stop
}catch{
    $ErrorMessage = $_.Exception.Message
    outputThis "Erro ao obter lista de vCenters do arquivo! `n $ErrorMessage"
}
$Form.Refresh()
$tamL = $VCStringlist.length
$Form.Refresh()
outputThis "Inicializando Script... `n Conectando em $tamL vCenters."
$Form.Refresh()
$conns = @()
$Form.Refresh()
#
# CONECTA AOS VCENTERS
#
$conns = connectvCenters $VCStringlist

$Form.Refresh()
$outputbox.Text =""
$Form.Refresh()

$Form.Refresh()
if($conns){
    outputThis "vCenters conectados! Aguardando comando..."
}else{
    outputThis "Não há vCenters conectados! Para utilizar as funções que exigem conexão com vCenter, reinicie o script."
}
#
#Show Form ===>
#
$Form.Visible = $false
$Form.ShowDialog()
}
################################################ End Form Creation Functions
#
#Criar Form com todos os itens, etc...
#
GenerateForm

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Impressive script !

I would try to use Timer Control in the form.

That would allow you to check at regular intervals if any of the Start-Job has finished, and if yes, retrieve the results and populate the fields in the form.

See for example Winforms and Timers


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

GuilhermeAlves
Enthusiast
Enthusiast
Jump to solution

Nice!

I'll see it tomorrow. Here In Brazil we call my state now of: "só o pó" (very tired) hehehe. Thanks for the tip!

--- Mensagem Original ---

De: "LucD" <communities-emailer@vmware.com>

Enviado: 18 de março de 2014 17:38

Para: "GuilhermeAlves" <guilhermestela@hotmail.com>

Assunto: New message: "Escaping from Powershell/Cli Form while running a command"

VMware Communities<https://communities.vmware.com/index.jspa>

Escaping from Powershell/Cli Form while running a comand

created by LucD<https://communities.vmware.com/people/LucD> in VMware vSphere™ PowerCLI - View the full discussion<https://communities.vmware.com/message/2358255#2358255>

Reply
0 Kudos
GuilhermeAlves
Enthusiast
Enthusiast
Jump to solution

So Luc... how can i retrieve the results and populate the fields in the form?

I can't save any return from the "Receive-Job" cmdlet... i think this is my very problem. If i could get and save in any variable a return from a job, then the timer would be very useful to check if the job has finished.

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

How do you try the results with the Receive-Job ?

Do you do something like this

foreach($job in Get-Job){
  Receive-Job -Job $job -OutVariable result

     # Work with the returned results in the variable $result

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
GuilhermeAlves
Enthusiast
Enthusiast
Jump to solution

Terrific Luc!

I'm only testing but now i know it'll work!! Thankssss :smileylaugh:

I've tested here to see if it Works and got the right output. That's what i wanted.


for($i=0;$i -lt 5;$i++){
    Start-Job -ArgumentList $i -ScriptBlock {$user = whoami;$rand=Get-random;$result = "$args $user $rand";$result}
}

$test = @()
foreach($job in Get-Job){
  $test += Receive-Job -Job $job -OutVariable result
  # Work with the returned results in the variable $result
}


And the $test variable returned the following output:

0 gastela 2055476192

1 gastela 1202982252

2 gastela 418272458

3 gastela 1294106128

4 gastela 1818567907

I'll let you know when i finish 😃 For now, thank you so much!!

Reply
0 Kudos
GuilhermeAlves
Enthusiast
Enthusiast
Jump to solution

i'm afraid that´s not so easy to do what i want...

i was trying to do the receive-job trick again but realize that the Object returned did not match what i need..

$block={       ############################################## Adding PowerCLI Snapin
              if(!(get-pssnapin | where {$_.name -eq "vmware.vimautomation.core"})) {
                  try {
                      add-pssnapin VMware.VimAutomation.Core
                  } catch {
                      $ErrorMessage = $_.Exception.Message
                      Write-Host "$ErrorMessage"
                  }
              }
              ##############################################

              Write-host "Connecting to server $args"
             Connect-VIServer -server $args -wa 0
          }

function connectvCenters{
          param($list)
          $JobArray =@()
      foreach($itemList in $list){
          try{
            $job = Start-Job -ArgumentList $itemList -ScriptBlock $block
            $JobArray +=$job
          }catch{
          $ErrorMessage = $_.Exception.Message
              Write-Host "Problema ao conectar o servidor '$vc' `n  $ErrorMessage"
          }
      }
      Return $JobArray
}

connectvCenters myvcenter

foreach($job in Get-Job){
   
  Wait-Job $job
  Receive-Job -Job $job -OutVariable test
  $test
   #Work with the returned results in the variable $result
}

i was thinking how to return a viconnection object. Instead, i'm getting an ArrayList returned...

PS Z:\VMware\SCRITPS\Datastore Visibility>> $test.GetType()

IsPublic IsSerial Name                                     BaseType                      
-------- -------- ----                                     --------                      
True     True     ArrayList                                System.Object                 

Reply
0 Kudos