title: PowerShell Closing open sessions
body: <p>I'm working on a large script where I run a <code>Foreach</code> loop, define variables in that loop and afterwards check if the <code>$Server</code> variable is pingable and if it is remotely accessible. </p>
  
  <p>For this I use the following functions coming from the PowerShell help:</p>
  
  <pre><code># Function to check if $Server is online
  Function CanPing ($Server) {
     $error.clear()
     $tmp = Test-Connection $Server -ErrorAction SilentlyContinue
  
     if ($?) {
         Write-Host "Ping succeeded: $Server"; Return $true
     }
     else {
          Write-Host "Ping failed: $Server."; Return $false
     }
  }
  
  # Function to check if $Server is remotely accessible
  Function CanRemote ($Server) {
      $s = New-PSSession $Server -Authentication Credssp -Credential $Credentials -Name "Test" -ErrorAction SilentlyContinue
  
      if ($s -is [System.Management.Automation.Runspaces.PSSession]) {
          Enter-PSSession -Session $s
          Exit-PSSession
          Write-Host "Remote test succeeded: $Server."; Return $true
      }
      else {
          Write-Host "Remote test failed: $Server."; Return $false
      }
  }
  
  # Execute functions to check $Server
  if ($Server -ne "UNC") {
  
      if (CanPing $Server) {
          if (-Not (CanRemote $Server)) {
          Write-Host "Exit loop REMOTE" -ForegroundColor Yellow
          continue
          }
      }
      else {
           Write-Host "Exit loop PING" -ForegroundColor Yellow
           continue # 'continue' to the next object and don't execute the rest of the code, 'break' exits the foreach loop completely
      }
  } 
  </code></pre>
  
  <p>Every time when I run this code, there is a process created on the remote server called <code>wsmprovhost.exe</code>. This process represents the PowerShell session, if the info I found on the web is correct. However, when doing <code>Get-PSSession $Server</code> there are no open sessions displayed in the PowerShell ISE, even though the processes are visible on the remote server and can only be killed with the Task Manager.</p>
  
  <p>When I run this code often the limit of open sessions is reached because every time a new process <code>wsmprovhost.exe</code> is added to the <code>$Server</code> and the command errors out. I've tried to solve this by adding <code>Exit-PSSession</code>to the code, but it doesn't close the session.</p>
  
  <p>Any help or ideas are more than welcome.</p>