Create a Visual Progress bar for a function

I have a query regarding creating a progress bar, I have look at the simple examples but I wanted to go another step and make it more visual appealing, I have come up with the below, however it fails t=to update the progress bar, just leaving it blank. In the function Ex I have a variable that is called $y which updates everytime a process has completed in the function. Using the $y++ - this is then stored in a file called progress and is updated after each process so the file looks like;

1
2
3…

I want to take $y and to update the progress bar, however from what I can see it needs to run the function Ex before it tries to update the progress bar; but this fails also. I do have this working but it cycles through a get-childitem and not a function I have created myself.

I include a copy of my code for reference.
Add-Type -assembly System.Windows.Forms

## -- Create The Progress-Bar
$ObjForm = New-Object System.Windows.Forms.Form
$ObjForm.Text = "Finishing Process"
$ObjForm.Height = 100
$ObjForm.Width = 500
$ObjForm.BackColor = "White"

$ObjForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$ObjForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen

## -- Create The Label
$ObjLabel = New-Object System.Windows.Forms.Label
$ObjLabel.Text = "Starting. Please wait ... "
$ObjLabel.Left = 5
$ObjLabel.Top = 10
$ObjLabel.Width = 500 - 20
$ObjLabel.Height = 15
$ObjLabel.Font = "Tahoma"
## -- Add the label to the Form
$ObjForm.Controls.Add($ObjLabel)

$PB = New-Object System.Windows.Forms.ProgressBar
$PB.Name = "PowerShellProgressBar"
$PB.Value = 0
$PB.Style="Continuous"

$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 500 - 40
$System_Drawing_Size.Height = 20
$PB.Size = $System_Drawing_Size
$PB.Left = 5
$PB.Top = 40
$ObjForm.Controls.Add($PB)

## -- Show the Progress-Bar and Start The PowerShell Script
$ObjForm.Show() | Out-Null
$ObjForm.Focus() | Out-NUll
$ObjLabel.Text = "Starting. Please wait ... "
$ObjForm.Refresh()

Start-Sleep -Seconds 1
Out-Null
## -- Execute The PowerShell Code and Update the Status of the Progress-Bar
$Ex = Ex
$Ex
$Counter = 0
gc $Progress
ForEach ($Item in $Progress) {
    ## -- Calculate The Percentage Completed
    $Counter++
    [Int]$Percentage = ($Counter/$Progress.Count)*100
    $PB.Value = $Percentage
    $ObjLabel.Text = "Creating an Xlsx File Please wait"
    #$ObjLabel.Text = "Found $counter $Criteria in $Search"
    $ObjForm.Refresh()
    Start-Sleep -Milliseconds 150
    # -- $Item.Name
    #"`t" + $Item.Path
    
}
$ObjForm.Close() 

You need to provide more of your code.

What does the function EX do?
It’s not shown in your post, so trying to step into your code (visually or in an editor) is not possible, because…

Ex : The term 'Ex' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path 
is correct and try again.
At line:44 char:7
+ $Ex = Ex
+       ~~
    + CategoryInfo          : ObjectNotFound: (Ex:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:47 char:4
+ gc $Progress
+    ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-Content], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand

There are also several spots in your post that are not really clear what they are or why they are there.
Like…

gc $Progress

What is Get-Content $Progress, as it’s not shown anywhere?
What’s in $Progress
BTW, that is also not the way to use Get-Content relative to variable content.

Based on your post, if you tried directly it would error out.

Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:48 char:4
+ gc $Progress
+    ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-Content], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand

OK, so here is all of my code,

To break down, it is to replicate robocopy and copy files from one location to another, keeping the folder structure, it then creates an excel spreadsheet using data collected in text files, I have all of this working, however I am trying to get it to update the progress bar in real-time, Ex is creating the excel spreadsheet. The code is quite lengthy as a warning, and the EX part of if is segregated for ease of reading.

Function Size{
    $file = '{0}myTypes.ps1xml' -f ([System.IO.Path]::GetTempPath()) 
$data = Get-Content -Path $PSHOME\FileSystem.format.ps1xml
$data -replace 'Length', @'

if($$_ -is [System.IO.FileInfo]) {
    $this=$$_.Length; $sizes='Bytes,KB,MB,GB,TB,PB,EB,ZB' -split ','
    for($i=0; ($this -ge 1kb) -and ($i -lt $sizes.Count); $i++) {$this/=1kb}
    $N=2; if($i -eq 0) {$N=0}
    "{0:N$($N)} {1}" -f $this, $sizes[$i]
} else { $null }

'@ | Set-Content -Path $file
Update-FormatData -PrependPath $file
}
Function Run{
    write-host "`n------------------------------------------------------- Start of Script -------------------------------------------------------" -ForegroundColor Green
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
$Script:Server = "\\" + [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a Server to search", "Server Choice")
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
$Script:Choice = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a File Path to search", "File Path Choice")  + "\"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
$Script:Ext = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a File type i.e. *.PST", "Location Choice") 
$Script:Criteria = "*." + $Ext.ToUpper()
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
#$FPath = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a path to copy to", "Location Choice") 
$Script:Path = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a folder to store the data", "Path Choice") + "\"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
#$Name = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a filename", "File Name Choice")
$Script:Search = $Server +"\"+ $Choice
$Script:FileName = $Path
$Script:Se = $Server +"\"+ $Choice
$Script:txt = ".txt"
$Script:stxt = "*" + $txt
$Script:FC = "Files Copied"
$Script:FD = "Folders"
$Script:FL = "Failed Copying"
$Script:RE1 = "Results0"
$Script:RE2 = "Results"
$Script:LC = "New Folders"
$Script:RE = "Info"
$Script:Exts = $Ext.ToUpper() +"'s"
$Script:Trial2 = $Path + $RE + $txt
$Script:Info = $Path + $FC + $txt
$Script:Trial = $Path + $FD + $txt
$Script:Type = $Path + $Exts + $txt 
$Script:Loc = $Path + $LC + $txt
$Script:Er= $Path + $FL + $txt
$Script:Ver = $Path + $RE1 + $txt
$Script:Ver1 = $Path + $RE2 + $txt
$Script:Fin = $Path+"File Copy Results for "+$Exts +".xlsx"
if( -Not (Test-Path -Path $Path ) )
{
    New-Item -ItemType directory -Path $Path |out-null
    
}
Else{
    [System.Windows.MessageBox]::Show('The directory already exists','Error','Ok','Error') 
    
}


        $result = Get-ChildItem -Path $Search -Recurse -Include $Criteria   -ErrorAction SilentlyContinue  
        $OP = $Result | Select DirectoryName
        write-host "------------------------------------------------------- Identifing files to be copied -------------------------------------------------------" -ForegroundColor Yellow

  
  $Result 
#Get-ChildItem -Path $Search -Recurse -Include *.pst -ErrorAction SilentlyContinue |
$Folders = (get-childitem -Path $Search | Where-Object { $_.PSIsContainer }).Count
#$Folders = $Folders | Format-Table FullName, LastwriteTime, Length

If (Test-Path $Search) {
	

	Add-Type -assembly System.Windows.Forms

	## -- Create The Progress-Bar
	$ObjForm = New-Object System.Windows.Forms.Form
	$ObjForm.Text = "Progress-Bar of searched folders"
	$ObjForm.Height = 100
	$ObjForm.Width = 500
	$ObjForm.BackColor = "White"

	$ObjForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
	$ObjForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen

	## -- Create The Label
	$ObjLabel = New-Object System.Windows.Forms.Label
	$ObjLabel.Text = "Starting. Please wait ... "
	$ObjLabel.Left = 5
	$ObjLabel.Top = 10
	$ObjLabel.Width = 500 - 20
	$ObjLabel.Height = 15
	$ObjLabel.Font = "Tahoma"
	## -- Add the label to the Form
	$ObjForm.Controls.Add($ObjLabel)

	$PB = New-Object System.Windows.Forms.ProgressBar
	$PB.Name = "PowerShellProgressBar"
	$PB.Value = 0
	$PB.Style="Continuous"

	$System_Drawing_Size = New-Object System.Drawing.Size
	$System_Drawing_Size.Width = 500 - 40
	$System_Drawing_Size.Height = 20
	$PB.Size = $System_Drawing_Size
	$PB.Left = 5
	$PB.Top = 40
	$ObjForm.Controls.Add($PB)

	## -- Show the Progress-Bar and Start The PowerShell Script
	$ObjForm.Show() | Out-Null
	$ObjForm.Focus() | Out-NUll
	$ObjLabel.Text = "Starting. Please wait ... "
	$ObjForm.Refresh()

	Start-Sleep -Seconds 1
 Out-Null
	## -- Execute The PowerShell Code and Update the Status of the Progress-Bar
    
	$result = Get-ChildItem -Path $Search -Recurse -Include $Criteria -ErrorAction SilentlyContinue 
	$Counter = 0
	ForEach ($Item In $Result) {
		## -- Calculate The Percentage Completed
		$Counter++
		[Int]$Percentage = ($Counter/$Result.Count)*100
		$PB.Value = $Percentage
		$ObjLabel.Text = "Scanning $Folders Folders For $Criteria in $Search"
        #$ObjLabel.Text = "Found $counter $Criteria in $Search"
		$ObjForm.Refresh()
		Start-Sleep -Milliseconds 150
		# -- $Item.Name
		#"`t" + $Item.Path
        
	}



Out-Null

#Sort-Object -Property DirectoryName  |

#Format-Table -Property $properties |

out-file $Info

$Search | out-file -Append $Trial 

$result | out-file -Append $Info

$result | Select Name | out-file -Append $Type

$OP | out-file -Append $Loc

gc $Loc | get-unique > $Trial2


$Script:CR = "`r`n"
$Script:CR2 = "Performing operation"
$Script:CR3 = $CR + $CR2
#"List of PDF's that Failed To Copy" + $CR + $CR + "--------------------------------------------------------------" +$CR | Out-file $Er
$des = $Path
#$PDFs= get-content $Type
$safe = Get-Content $Trial

#$Ten = @($Criteria)
$safe | ForEach-Object{
    #find drive-delimeter
    
    $first=$_.IndexOf("\\");
    
    if($first -eq 0){
        #stripe it
    $newdes=Join-Path -Path $des -ChildPath @($_.Substring(0,1)+$_.Substring(2))[0]    
        }
        $newdes=Join-Path -Path $des -ChildPath $_
    $err=0
    $fr=0
    $folder=Split-Path -Path $newdes -Parent
    $folders=Split-Path -Path $newdes -leaf
    #$fy = $folder + "\" +$folders
    #check if folder exists"
    
   $void=Get-Item $newdes -ErrorVariable err  -ErrorAction SilentlyContinue #-verbose
   If(!(Test-Path -Path $newdes) ){
    $err=1
   }
     if($err.Count -ne 0){
        #create when it doesn't
        
        $void=New-Item -Path $folder -ItemType Directory #-verbose
        
        } 
            #$void=Copy-Item -Path $_ -destination $newdes  -Force -Verbose
            
            $void=Copy-Item -Path $_ -destination $folder -Filter $Criteria -Recurse -Container -Force -ErrorVariable fr  -ErrorAction SilentlyContinue -verbose 4>$Ver
            #write-host $void -ForegroundColor White
            write-host "------------------------------------------------------- Copying Files to selected location -------------------------------------------------------" -ForegroundColor Yellow
            foreach($re in $fr){
            $RR = $re[0].CategoryInfo.TargetName.ToString()
            $X5 = $re[0].Exception.Message.ToString()
            $X6 = $re[0].TargetObject.DirectoryName.ToString()
            "------------------------ FILE ERROR AT LOCATION ------------------------"+ $CR  + $X6 + $CR +  "------------------------ ERROR DETAILS ------------------------"+ $CR + $X5 + $CR  + "------------------------ FILENAME ------------------------ "+ $CR + $RR + $CR | Out-file -Append $Er
            }
    #powershell ".\File Copy and Move56" >  $Ver
        }
        ForEach ($l in (Get-Content $Ver ) ){
            $l -replace $CR2,$CR3   | Out-file $Ver1 -Append
        }
        Remove-Item $Ver

        $CR | Out-File -Append $Trial
    }
    $ObjForm.Close()
    #Write-Host "`n"
    
}
    ################### Ex ###################
    Function Ex{
        $Script:y = 0
        $Script:Pro = "Progress"
        $Script:Progress = $Path + $Pro + $txt
        write-host "------------------------------------------------------- Creating Xlsx File -------------------------------------------------------" -ForegroundColor White
        $Script:excelapp = New-Object -comobject Excel.Application
        $excelapp.DisplayAlerts = $false
        $Script:excelapp.Visible = $false
        $Script:workbook = $excelapp.Workbooks.Add()
        $y++ |Out-File -Append $Progress
        $Script:worksheet1 = $workbook.WorkSheets.Item(1)
        $y++ #|Out-File -Append $Progress
        $worksheet1.name = $FC
        $y++ |Out-File -Append $Progress
        $cells=$Worksheet1.Cells
        $deleimter = $CR
        $Script:Content = Get-Content $Info
        $y++ |Out-File -Append $Progress
        $numOfRows = $Content.Length
        $numOfColumns = $Content[0].split($deleimter).Count
        for ($i=0; $i -lt $numOfRows ;$i++)
        {
        $rowData = $Content[$i].split($deleimter)
        for ($j=0; $j -lt $numOfColumns; $j++)
        {
        $cellData = $rowData[$j]
        $cells.item($i+1,$j+1) = $cellData
        $y++ |Out-File -Append $Progress
        }
           }
           $worksheet1.Cells.Item(1,2) = "These Are the files that have been Copied"
           $worksheet1.Cells.Item(1,2).Font.Bold = $true
           $worksheet1.Cells.Item(1,2).Font.Size = 14
           $worksheet1.Cells.Item(1,2).Font.ColorIndex =41           
           $worksheet1.Cells.Item(1,2).HorizontalAlignment = -4108
           $worksheet1.Cells.Item(1,2).Font.Underline = $true
           $Range = $worksheet1.Range("A1:H1")
           $Range.Merge()
           $y++ |Out-File -Append $Progress
       ################### Ex2 ###################
        $Script:worksheet2 = $workbook.WorkSheets.add()
        $y++ |Out-File -Append $Progress
        $worksheet2.name = $FD
        $y++ |Out-File -Append $Progress
        $cells=$worksheet2.Cells
        $Script:Content = Get-Content $Trial2
        $y++ |Out-File -Append $Progress
        $deleimter = $CR
        $numOfRows = $Content.Length
        $numOfColumns = $Content[0].split($deleimter).Count
        for ($i=0; $i -lt $numOfRows ;$i++)
        {
        $rowData = $Content[$i].split($deleimter)
        for ($j=0; $j -lt $numOfColumns; $j++)
        {
        $cellData = $rowData[$j]
        $cells.item($i+1,$j+1) = $cellData
        $y++ |Out-File -Append $Progress
        }
    }
    
           $range = $worksheet2.Range("A1:A1")
           $range.Insert(-4121) | Out-Null
           $worksheet2.Cells.Item(1,2) = "These Are the folders that have been accessed"
           $worksheet2.Cells.Item(1,2).Font.Bold = $true
           $worksheet2.Cells.Item(1,2).Font.Size = 14
           $worksheet2.Cells.Item(1,2).Font.ColorIndex =41 
           $worksheet2.Cells.Item(1,2).HorizontalAlignment = -4108
           $worksheet2.Cells.Item(1,2).Font.Underline = $true
           $Range = $worksheet2.Range("A1:H1")
           $Range.Merge()
           $y++ |Out-File -Append $Progress
       ################### Ex3 ###################
       
       $Script:worksheet3 = $workbook.WorkSheets.add()
       $worksheet3.name = $FL
       $y++ |Out-File -Append $Progress
       $cells=$worksheet3.Cells
       $Script:Content = Get-Content $Er
       $y++ |Out-File -Append $Progress
       $deleimter = $CR
       $numOfRows = $Content.Length
       $numOfColumns = $Content[0].split($deleimter).Count
       for ($i=0; $i -lt $numOfRows ;$i++)
       {
       $rowData = $Content[$i].split($deleimter)
       for ($j=0; $j -lt $numOfColumns; $j++)
       {
       $cellData = $rowData[$j]
       $cells.item($i+1,$j+1) = $cellData
       $y++ |Out-File -Append $Progress
       }
   }
   
      $range = $worksheet3.Range("A1:A2")
      $range.Insert(-4121) | Out-Null
      $worksheet3.Cells.Item(1,2) = "These Are the files that have failed to copy"
      $worksheet3.Cells.Item(1,2).Font.Bold = $true
      $worksheet3.Cells.Item(1,2).Font.Size = 14
      $worksheet3.Cells.Item(1,2).Font.ColorIndex =41 
      $worksheet3.Cells.Item(1,2).HorizontalAlignment = -4108
      $worksheet3.Cells.Item(1,2).Font.Underline = $true
      $Range = $worksheet3.Range("A1:H1")
      $Range.Merge()
      $y++ |Out-File -Append $Progress
        ################### Ex4 ###################
        
       $Script:worksheet4 = $workbook.WorkSheets.add()
       $worksheet4.name = $Exts
       $y++ |Out-File -Append $Progress
       $cells=$worksheet4.Cells
       $Script:Content = Get-Content $Type
       $y++ |Out-File -Append $Progress
       $deleimter = $CR
       $numOfRows = $Content.Length
       $numOfColumns = $Content[0].split($deleimter).Count
       for ($i=0; $i -lt $numOfRows ;$i++)
       {
       $rowData = $Content[$i].split($deleimter)
       for ($j=0; $j -lt $numOfColumns; $j++)
       {
       $cellData = $rowData[$j]
       $cells.item($i+1,$j+1) = $cellData
       $y++ |Out-File -Append $Progress
       }
   }
   
       $range = $worksheet4.Range("A1:A4")
       $range.Delete()
       $range = $worksheet4.Range("A1:A2")
       $range.Insert(-4121) | Out-Null
       $worksheet4.Cells.Item(1,2) = "These Are the files that have been copied"
       $worksheet4.Cells.Item(1,2).Font.Bold = $true
       $worksheet4.Cells.Item(1,2).Font.Size = 14
       $worksheet4.Cells.Item(1,2).Font.ColorIndex =41 
       $worksheet4.Cells.Item(1,2).HorizontalAlignment = -4108
       $worksheet4.Cells.Item(1,2).Font.Underline = $true
       $Range = $worksheet4.Range("A1:H1")
       $Range.Merge()
       $y++ |Out-File -Append $Progress
        ################### Ex5 ###################
        
        $Script:worksheet5 = $workbook.WorkSheets.add()
        $worksheet5.name = $RE2
        $y++ |Out-File -Append $Progress
        $cells=$worksheet5.Cells
        $Content = Get-Content $Ver1
        $y++ |Out-File -Append $Progress
        $deleimter = $CR
        $numOfRows = $Content.Length
        $numOfColumns = $Content[0].split($deleimter).Count
        for ($i=0; $i -lt $numOfRows ;$i++)
        {
        $rowData = $Content[$i].split($deleimter)
        for ($j=0; $j -lt $numOfColumns; $j++)
        {
        $cellData = $rowData[$j]
        $cells.item($i+1,$j+1) = $cellData
        $y++ |Out-File -Append $Progress
        }
    }
    
        $range = $worksheet5.Range("A1:A1")
        $range.Insert(-4121) | Out-Null
        $worksheet5.Cells.Item(1,2) = "These Are the results of the copy"
        $worksheet5.Cells.Item(1,2).Font.Bold = $true
        $worksheet5.Cells.Item(1,2).Font.Size = 14
        $worksheet5.Cells.Item(1,2).Font.ColorIndex =41 
        $worksheet5.Cells.Item(1,2).HorizontalAlignment = -4108
        $worksheet5.Cells.Item(1,2).Font.Underline = $true
        $Range = $worksheet5.Range("A1:H1")
        $Range.Merge()
        $y++ |Out-File -Append $Progress
        ################### Ex Format ###################
        $y++ |Out-File -Append $Progress
        $workbook.WorkSheets.Item($Worksheet1.name).move($workbook.WorkSheets.item(1))
        $workbook.WorkSheets.Item($worksheet2.name).move($workbook.WorkSheets.item(2))
        $workbook.WorkSheets.Item($Worksheet3.name).move($workbook.WorkSheets.item(3))
        $workbook.WorkSheets.Item($Worksheet4.name).move($workbook.WorkSheets.item(4))
        $workbook.WorkSheets.Item($Worksheet5.name).move($workbook.WorkSheets.item(5))
        $workbook.WorkSheets.Item($worksheet1.Name).Select()
        ################### Ex End ###################
         $y++ |Out-File -Append $Progress
            $workbook.SaveAs($Fin,51)
            $excelapp.Quit()
            write-host "------------------------------------------------------- Xlsx File Completed -------------------------------------------------------" -ForegroundColor White

            $y =0
}
Size
Run 
Add-Type -assembly System.Windows.Forms

## -- Create The Progress-Bar
$ObjForm = New-Object System.Windows.Forms.Form
$ObjForm.Text = "Finishing Process"
$ObjForm.Height = 100
$ObjForm.Width = 500
$ObjForm.BackColor = "White"

$ObjForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$ObjForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen

## -- Create The Label
$ObjLabel = New-Object System.Windows.Forms.Label
$ObjLabel.Text = "Starting. Please wait ... "
$ObjLabel.Left = 5
$ObjLabel.Top = 10
$ObjLabel.Width = 500 - 20
$ObjLabel.Height = 15
$ObjLabel.Font = "Tahoma"
## -- Add the label to the Form
$ObjForm.Controls.Add($ObjLabel)

$PB = New-Object System.Windows.Forms.ProgressBar
$PB.Name = "PowerShellProgressBar"
$PB.Value = 0
$PB.Style="Continuous"

$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 500 - 40
$System_Drawing_Size.Height = 20
$PB.Size = $System_Drawing_Size
$PB.Left = 5
$PB.Top = 40
$ObjForm.Controls.Add($PB)

## -- Show the Progress-Bar and Start The PowerShell Script
$ObjForm.Show() | Out-Null
$ObjForm.Focus() | Out-NUll
$ObjLabel.Text = "Starting. Please wait ... "
$ObjForm.Refresh()

Start-Sleep -Seconds 1
Out-Null
## -- Execute The PowerShell Code and Update the Status of the Progress-Bar
$Ex = Ex
$Ex
$Counter = 0
#gc $Progress
ForEach ($Item in $Ex) {
    ## -- Calculate The Percentage Completed
    $Counter++
    [Int]$Percentage = ($Counter/$y.Count)*100
    $PB.Value = $Percentage
    $ObjLabel.Text = "Creating an Xlsx File Please wait"
    #$ObjLabel.Text = "Found $counter $Criteria in $Search"
    $ObjForm.Refresh()
    Start-Sleep -Milliseconds 150
    # -- $Item.Name
    #"`t" + $Item.Path
    
}
$ObjForm.Close()

Out-Null
Get-ChildItem $Path -Include  $stxt -Recurse | Remove-Item
#Remove-Item $Trial2
#Remove-Item $Info
#Remove-Item $Type
#Remove-Item $Trial
#Remove-Item $Loc
#Remove-Item $Er
#Remove-Item $Ver1

    write-host "`n This is the location you chose to copy from `n" $Se
    write-host "`n This is the file extension you chose `n" $Criteria
    write-host "`n This is location you chose to copy the files to `n"  $Path
    
    write-host "`n------------------------------------------------------- End of Script -------------------------------------------------------" -ForegroundColor Blue

Please Remove