How to export a CSV file in #PowerShell

How to export a CSV file in #PowerShell

begin

How do I export a CSV: The method?

  1. Define an object
  2. Get an array of those objects
  3. Use export-csv commandlet with the options you need to export to a csv file

Define an an object: Example

#A windows task scheduler object

class TaskObject
{
    $name
    $start_dt
    $freq
    $script
    $status
    [string]$cmd #if needed, use type

}

Get an array of those objects

#Get an array of TaskObjects
$taskObjArray = getSomeFunction()

#pick the fields you like using Select-Object

$newTaskObjArray = $taskObjArray | Select-Object -Property name, freq

#Write those to a csv file

#dir = "c:\some-dir"

#Call the write to csv function above

writeToCSV -dir $dir -taskObjList $na

Write the array to a CSV fle

function writeToCSV($dir, $taskObjList)
{
    #Get a nice file path
    $filepath = $dir + "\exported-tasks.csv"

    p -message "Going to write a csv file: $filepath"

    #select the fields you like
    $r = $taskObjList | Export-Csv -Path $filepath -NoTypeInformation

    #done
    p -message "Finished writing a csv file: $filepath"
}

Where is Export-CSV documented?

Powershell docs on Export-CSV link

You can see at this site documentation on other comandlets as well including Select-Object.

end

要查看或添加评论,请登录

Satya Komatineni的更多文章

社区洞察

其他会员也浏览了