title: Powershell variable export-CSV cache?
body: <p>I am working on a script by Richard L. Mueller (<a href="http://www.rlmueller.net/PowerShell/PSLastLogon.txt" rel="nofollow">http://www.rlmueller.net/PowerShell/PSLastLogon.txt</a>)</p>
  
  <pre><code>Trap {"Error: $_"; Break;}
  
  $D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
  $Domain = [ADSI]"LDAP://$D"
  $Searcher = New-Object System.DirectoryServices.DirectorySearcher
  $Searcher.PageSize = 200
  $Searcher.SearchScope = "subtree"
  
  $Searcher.Filter = "(&amp;(objectCategory=person)(objectClass=user))"
  $Searcher.PropertiesToLoad.Add("samAccountName") &gt; $Null
  $Searcher.PropertiesToLoad.Add("lastLogon") &gt; $Null
  
  $arrUsers = @{}
  
  
  ForEach ($DC In $D.DomainControllers)
  {
  $Server = $DC.Name
  $Searcher.SearchRoot = "LDAP://$Server/" + $Domain.distinguishedName
  $Results = $Searcher.FindAll()
  ForEach ($Result In $Results)
  {
      $DN = $Result.Properties.Item("samAccountName")
      $LL = $Result.Properties.Item("lastLogon")
      If ($LL.Count -eq 0)
      {
          $Last = [DateTime]0
      }
      Else
      {
          $Last = [DateTime]$LL.Item(0)
      }
      If ($Last -eq 0)
      {
          $LastLogon = $Last.AddYears(1600)
      }
      Else
      {
          $LastLogon = $Last.AddYears(1600).ToLocalTime()
      }
      If ($arrUsers.ContainsKey("$DN"))
      {
          If ($LastLogon -gt $arrUsers["$DN"])
          {
              $arrUsers["$DN"] = $LastLogon
          }
      }
      Else
      {
          $arrUsers.Add("$DN", $LastLogon)
      }
  }
  }
  
  
  $inactiveusers = @()
  $Users = $arrUsers.Keys
  ForEach ($DN In $Users)
  {
  $Date = $arrUsers["$DN"]
  "$DN;$Date"
  $inactiveusers += $DN
  $inactiveusers += $Date
  $inactiveusers | export-csv "c:\test.csv"
  }
  </code></pre>
  
  <p>Thinking to store the info to another array, I added the those line start with $inactiveusers (total of 4 lines). However the CSV exported does not gives me the correct result, instead of listing the user samAccountName &amp; lastlogon, the length of the samAccountName is returned.</p>
  
  <p>Further to this, since then I cannot export the same variable in my another script even the script is just simple as:</p>
  
  <pre><code>$inactiveusers = "Test"
  $inactiveusers | Export-Csv c:\test.csv
  write-host $inactiveusers
  </code></pre>
  
  <p>The CSV exported still give me the length of the string "Test", <strong>however the write-host result is correct.</strong>
  I tried remove-variable, logoff &amp; login back but both without luck.
  I am not sure where the cache stored. I can work on the script later on but first I want to able to export this variable to CSV in another script. <br> appreciate anyone can give me some hint</p>