Q:

PowerShell SharePoint Online ExecuteQuery Error - Timed Out

This one has been puzzling me for days now... It works more than half the time, but will often give me this error upon calling the ExecuteQuery() command: 

Exception calling "ExecuteQuery" with "0" argument(s): "The operation has timed out"

The PowerShell: 
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webURL) 
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credentials.UserName,$Credentials.Password) 

$web = $ctx.Web  
$ctx.Load($web) 

#Retrieve Library
$list = $ctx.Web.Lists.GetByTitle($ITPurchaseRequestListName)
$ctx.load($list)

$files = $list.rootFolder.files
$ctx.load($files)
$ctx.executeQuery()

##########
if((test-path $tempPath) -eq $False)
{
    new-item -itemtype directory -path $temppath
}

foreach($file in $files)
{
    $ctx.load($file)
    $ctx.executeQuery()

    $fileRef = $file.ServerRelativeURL
    $fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($ctx, $fileRef);

    $fileName = $tempPath + $file.Name
    $fileStream = [System.IO.File]::Create($fileName)
    $fileInfo.Stream.CopyTo($fileStream);

    $fileStream.Close()

    start-sleep -seconds 2
}

If I kill the console session and start a new PowerShell window, it'll work for a few runs and then conk out again. Any ideas?

A:

In addition to the other comments and suggestions, the folks at 6sc.com were able to help me identify the root cause which was a missing stream.close() in the for loop. 
foreach($file in $results)
{

    $fileRef = $file["FileRef"];
    $fileName = $tempPath + $file["FileLeafRef"];

    $fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($ctx, $fileRef);
    $fileStream = [System.IO.File]::Create($fileName);
    $fileInfo.Stream.CopyTo($fileStream);

    $fileStream.Close();
    $fileInfo.Stream.Close();
}

