title: ArrayList not displaying when first referenced in function
body: <p>Facing a couple logistical issues in PowerShell - clearly I'm missing a basic concept:</p>
  <p>Setup: Create the menu.ps1 file (shown below), launch PowerShell 7.2.2 and call the file locally.</p>
  <p>Issues:</p>
  <ol>
  <li>The first time you choose option 1 for the ArrayList (<code>$psArrayList</code>), it does not display (although we see from the initial screen load that the items are populated).  If you return to the menu and choose option 1 again, it will display on the second pass.  (<code>$psArray</code> does load fine on first try, so is this is a type issue.?)</li>
  <li>When the script ends, <code>$psArrayList</code> and <code>$psArray</code> are still in the current session variables, as indicated by: <code>Get-Variable psArray*</code>.  Even if I instantiate them with <code>$script:psArrayList = [System.Collections.ArrayList]@()</code> and <code>$script:psArray = @()</code> they seem to stay within the session scope.  Is there a &quot;right&quot; way to clear them when the ps1 ends?</li>
  </ol>
  <p>menu.ps1 contents:</p>
  <pre><code>$psArrayList = [System.Collections.ArrayList]@()
  # example of populating later in function etc...
  $psArrayList.Add([pscustomobject]@{name=&quot;bird&quot;;color=&quot;blue&quot;})
  $psArrayList.Add([pscustomobject]@{name=&quot;cat&quot;;color=&quot;orange&quot;})
  $psArrayList.Add([pscustomobject]@{name=&quot;bear&quot;;color=&quot;brown&quot;})
  
  $psArray = @()
  # example of populating later in function etc...
  $psArray += &quot;dog&quot;
  $psArray += &quot;fish&quot;
  $psArray += &quot;squirrel&quot;
  
  function End-Script {
      Remove-Variable psArray*
      Exit
  }
      
  function Display-Menu { 
      [int]$choice=-1
  
      Write-Host &quot;This is a menu...&quot; -ForegroundColor Green
  
      Write-Host &quot;Here are your options:&quot;
      Write-Host
      Write-Host &quot;`t1 - ArrayList&quot;
      Write-Host &quot;`t2 - Array&quot;
      Write-Host &quot;`t0 - quit (do nothing)&quot;
      Write-Host
  
      while ($choice -lt 0) { $choice= Read-Host -Prompt &quot;Choose 1-2 (or 0 to quit)&quot; }
      
      Process-Menu($choice)
  }
  
  function Process-Menu([int]$choice) {   
      switch($choice) {
          1 { Write-Host &quot;You chose ArrayList:&quot;; Write-Output $psArrayList }
          2 { Write-Host &quot;You chose Array:&quot;; Write-Output $psArray }
          0 { Write-Host &quot;You chose to quit. Exiting.&quot;; End-Script }  
      }
      
      $yn=&quot;&quot;
      while ($yn -eq &quot;&quot;) { $yn= Read-Host -Prompt &quot;Return to main menu? (y/n)&quot; }
      
      if ($yn -eq &quot;y&quot;) { Display-Menu } else { Write-Host &quot;Ending...&quot;; End-Script }
  }
  
  Display-Menu
  </code></pre>