PoshCode Logo PowerShell Code Repository

Export-CSV -Append (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1590"></script>download | new post

Add this function to your profile to make Export-CSV cmdlet handle -Append parameter

  1. #Requires -Version 2.0
  2.  
  3. <#
  4.   This Export-CSV behaves exactly like native Export-CSV
  5.   However it has one optional switch -Append
  6.   Which lets you append new data to existing CSV file: e.g.
  7.   Get-Process | Select ProcessName, CPU | Export-CSV processes.csv -Append
  8.  
  9.   For details, see
  10.   http://dmitrysotnikov.wordpress.com/2010/01/19/export-csv-append/
  11.  
  12.   (c) Dmitry Sotnikov
  13. #>
  14.  
  15. function Export-CSV {
  16. [CmdletBinding(DefaultParameterSetName='Delimiter',
  17.   SupportsShouldProcess=$true, ConfirmImpact='Medium')]
  18. param(
  19.  [Parameter(Mandatory=$true, ValueFromPipeline=$true,
  20.            ValueFromPipelineByPropertyName=$true)]
  21.  [System.Management.Automation.PSObject]
  22.  ${InputObject},
  23.  
  24.  [Parameter(Mandatory=$true, Position=0)]
  25.  [Alias('PSPath')]
  26.  [System.String]
  27.  ${Path},
  28.  
  29.  #region -Append (added by Dmitry Sotnikov)
  30.  [Switch]
  31.  ${Append},
  32.  #endregion
  33.  
  34.  [Switch]
  35.  ${Force},
  36.  
  37.  [Switch]
  38.  ${NoClobber},
  39.  
  40.  [ValidateSet('Unicode','UTF7','UTF8','ASCII','UTF32','BigEndianUnicode','Default','OEM')]
  41.  [System.String]
  42.  ${Encoding},
  43.  
  44.  [Parameter(ParameterSetName='Delimiter', Position=1)]
  45.  [ValidateNotNull()]
  46.  [System.Char]
  47.  ${Delimiter},
  48.  
  49.  [Parameter(ParameterSetName='UseCulture')]
  50.  [Switch]
  51.  ${UseCulture},
  52.  
  53.  [Alias('NTI')]
  54.  [Switch]
  55.  ${NoTypeInformation})
  56.  
  57. begin
  58. {
  59.  # This variable will tell us whether we actually need to append
  60.  # to existing file
  61.  $AppendMode = $false
  62.  
  63.  try {
  64.   $outBuffer = $null
  65.   if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
  66.   {
  67.       $PSBoundParameters['OutBuffer'] = 1
  68.   }
  69.   $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Export-Csv',
  70.     [System.Management.Automation.CommandTypes]::Cmdlet)
  71.        
  72.        
  73.         #String variable to become the target command line
  74.         $scriptCmdPipeline = ''
  75.  
  76.         # Add new parameter handling
  77.         #region Dmitry: Process and remove the Append parameter if it is present
  78.         if ($Append) {
  79.  
  80.                 $PSBoundParameters.Remove('Append') | Out-Null
  81.    
  82.   if ($Path) {
  83.    if (Test-Path $Path) {        
  84.     # Need to construct new command line
  85.     $AppendMode = $true
  86.    
  87.     if ($Encoding.Length -eq 0) {
  88.      # ASCII is default encoding for Export-CSV
  89.      $Encoding = 'ASCII'
  90.     }
  91.    
  92.     # For Append we use ConvertTo-CSV instead of Export
  93.     $scriptCmdPipeline += 'ConvertTo-Csv -NoTypeInformation '
  94.    
  95.     # Inherit other CSV convertion parameters
  96.     if ( $UseCulture ) {
  97.      $scriptCmdPipeline += ' -UseCulture '
  98.     }
  99.     if ( $Delimiter ) {
  100.      $scriptCmdPipeline += " -Delimiter '$Delimiter' "
  101.     }
  102.    
  103.     # Skip the first line (the one with the property names)
  104.     $scriptCmdPipeline += ' | Foreach-Object {$start=$true}'
  105.     $scriptCmdPipeline += '{if ($start) {$start=$false} else {$_}} '
  106.    
  107.     # Add file output
  108.     $scriptCmdPipeline += " | Out-File -FilePath '$Path' -Encoding '$Encoding' -Append "
  109.    
  110.     if ($Force) {
  111.      $scriptCmdPipeline += ' -Force'
  112.     }
  113.  
  114.     if ($NoClobber) {
  115.      $scriptCmdPipeline += ' -NoClobber'
  116.     }  
  117.    }
  118.   }
  119.  }
  120.  
  121.  
  122.  
  123.  $scriptCmd = {& $wrappedCmd @PSBoundParameters }
  124.  
  125.  if ( $AppendMode ) {
  126.   # redefine command line
  127.   $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
  128.       $scriptCmdPipeline
  129.     )
  130.  } else {
  131.   # execute Export-CSV as we got it because
  132.   # either -Append is missing or file does not exist
  133.   $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
  134.       [string]$scriptCmd
  135.     )
  136.  }
  137.  
  138.  # standard pipeline initialization
  139.  $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
  140.  $steppablePipeline.Begin($PSCmdlet)
  141.  
  142.  } catch {
  143.    throw
  144.  }
  145.    
  146. }
  147.  
  148. process
  149. {
  150.   try {
  151.       $steppablePipeline.Process($_)
  152.   } catch {
  153.       throw
  154.   }
  155. }
  156.  
  157. end
  158. {
  159.   try {
  160.       $steppablePipeline.End()
  161.   } catch {
  162.       throw
  163.   }
  164. }
  165. <#
  166.  
  167. .ForwardHelpTargetName Export-Csv
  168. .ForwardHelpCategory Cmdlet
  169.  
  170. #>
  171.  
  172. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me