title: My Powershell loop is overwriting the previous excel entry. Using Export-CSV -append duplicates entries
body: <p>Powershell is definitely not one of my "strengths" but every once in a while I try to script something to automate a manual task.  Anyway, here is my problem.  The script as is WORKS and WILL export a csv file and sort by the Hostname header.  My issues is there has got to be a better way of doing this?</p>
  
  <pre><code>#Clear the output screen
  cls
  
  #set the working directory to where the script and text files are located (must be same directory)
  $scriptdir = Split-Path -Parent $PSCommandPath
  cd $scriptdir
  
  #set fileNamePaths for Export-Csv No Sort and Sorted to excel
  $FilePathNS = "D:\PowerShell_Scripts\HP_Inventory\OAInfoAll_NoSort.csv"
  $FilePathSort = "D:\PowerShell_Scripts\HP_Inventory\OAInfoAll.csv"
  
  #set up the ip subnet import
  $path = ".\EnclosureSubnets.txt"
  $ip = Get-Content $path
  
  #Loop to find OA information
  foreach ($subnet in $ip) {
  
      $OAS = Find-HPOA $subnet -Timeout 250 -Verbose
      $OAS | where {$_.Role -eq "Active"} | Export-Csv -NoTypeInformation -Append $FilePathNS
  }
  
  #Sort AOInfoAll.csv by hostname
  Import-Csv $FilePathNS | Sort-Object Hostname | Export-Csv $FilePathSort -NoTypeInformation
  </code></pre>
  
  <p>If I take out the append then the loop will overwrite the previous entry and I will only end up with 2 IPs and 2 Hostnames.  Append fixes this BUT when I run the script again I get duplicate/repeating entries.</p>
  
  <p>Also, I've tried using the Sort-Object Hostname inside the loop but it only sorts each individual entry as they are written. Here is an example (IPs and Hostnames are made up):</p>
  
  <pre><code>IP                  Hostname
  192.168.1.10        chassis03
  192.168.1.12        chassis05
  192.168.2.16        chassis01
  192.168.2.18        chassis02
  192.168.3.14        chassis07
  192.168.3.16        chassis08
  </code></pre>
  
  <p>So while my script works I'd like some feedback from "The Pros"  Thanks in advance!</p>