Learn about Windows PowerShell
Summary: Learn how to use Windows PowerShell to read CSV files and create files and folders.
Microsoft Scripting Guy Ed Wilson here. This past week has been fun. I enjoy talking about comma-separated value files (CSV) because they are very flexible, and Windows PowerShell makes working with them really easy.
One of the cool things that can be done using a CSV file was only alluded to in yesterday’s post, Use a CSV File to Populate Parameters of PowerShell Cmdlets.
In yesterday’s article, I piped information from a CSV file to the Get-WmiObject cmdlet. The problem is that the Get-WmiObject cmdlet does not accept piped input for either the class or computername parameter.
However, the New-Item cmdlet does accept piped input. When a cmdlet accepts piped input, it will automatically match column names from a CSV file with parameter names of the cmdlet receiving the piped input. This allows for some extremely powerful scenarios. Here are the steps for this scenario:
Suppose I create a CSV file that contains a file system layout. In that file, I specify the name of the folder and the names of files I want to create in that folder. I use the column names of path and itemtype because those are the parameter names used by the New-Item cmdlet. A sample CSV file that meets these requirements is shown in the following figure
After I have created my file, the Windows PowerShell command itself is trivial. I use the Import-CSV cmdlet to read the CSV file, and I pipe the results to the New-Item cmdlet. This command is shown here:
Import-Csv C:\fso\FilesAndFolders.csv | New-Item
The use of the command to read a CSV file and create files and folders along with the associated output are shown in the following figure.
When this command runs, the following is displayed in Windows Explorer.
That is about all there is to reading a CSV file and automatically creating files and folders. Given the Windows PowerShell providers that work with New-Item, this one scenario and one cmdlet provide lots of possibilities. And this is only one cmdlet. I will leave it to you to explore and see what you can come up with. Let me know.
I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at email@example.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
WOW! This is even a little bit better, than the solution to yesterday's problem!
We only have to name the columns properly, according to the names of the cmdlet's paramters and the whole job is done! That is pretty cool ..
@Klaus Schulte Thank you for the comment. I thought it was pretty cool when I figured it out. I also think it can be a really powerful solution.
Thanks a lot! Its simple and Works!