Use PowerShell to Automatically Create a CSV File

Use PowerShell to Automatically Create a CSV File

  • Comments 1
  • Likes

Summary: Learn how to use Windows PowerShell to automatically create a CSV file.

 

Microsoft Scripting Guy Ed Wilson here. I am about finished playing around with CSV files for the time being. I do not always use the ConvertTo-CSV or the Export-CSV cmdlet. There are times that I write code and create my own CSV file from scratch. An example of this is the CreateCSVFile.ps1 script that follows:

CreateCSVFile.ps1

1..5 | ForEach-Object -begin { "path,itemtype" } -process{

 "c:\folder$_,directory"

 for($i=0; $i -le 10; $i++) {"c:\folder$_\file$i.txt,file"}} |

 Out-File c:\fso\filesAndFolders.csv -Encoding ascii -Force

This script creates a CSV file that I can use to create a nested folder hierarchy. It is useful when testing certain applications, or for testing a Windows PowerShell script. I create five folders, and inside each folder I create 11 files. The folders are off the root and are named Folder1, Folder2, Folder3, Folder4, and Folder5. The files are named file0, file1, and so on through file10.

When using the Foreach-Object, I use the begin parameter to perform an action once. Inside the process block, I create the path to the folder, and I include the itemtype of directory. Next, I use a loop to create the path to the files.

The newly created CSV file is shown in the following figure.

Image of newly created CSV file

I use the Import-CSV cmdlet to import the CSV file, and I pipe it to the New-Item cmdlet as shown here:

Import-Csv C:\fso\FilesAndFolders.csv | New-Item

The command and associated output are shown in the following figure.

Image of command and associated output

One of the folders and associated files is shown in the following figure.

Image of folder and files

As you can see, there are times when it is easier to use a little bit of code to create the CSV file. This makes it a lot easier when it comes time to import the file and to pipeline it to another cmdlet.

 

This is all for today. I hope you have a great day. See you next week.

 

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

 

 

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Hi Ed,

    this is another nice add-on to our scripting bag!

    You can easily build your own CSV files that are suitable to automatic processing later on.

    It's really a unique feature that powershell can match parameters by property name through the pipeline!

    That's one of the outstanding PS feautures!

    Klaus.