[Powershell] Create files in a directory from a CSV list

I’ve recently been using Powershell more and more to replace either broken and/or ageing ‘batch’ files at work plus also come personal projects I’ve been working on.

Some of them took a bit of digging around between various sites/blogs to put together, so I’ve decided to re-post them with a final solution.

Warning: I’m a pretty crap blogger, so don’t expect regular updates!

Anyway, this one is I wanted to test a copy and rename script but needed some testing data first. So this creates a file in a folder with the name taken from a list in a CSV. The ID didn’t have a file extension so I’m randomly creating one from a small list.

Brief: Take a list of ID’s from a CSV and create a file in a folder using the ID as the filename with a random file extension.

$docext = @("msg","docx","doc","xlsx","xls","pdf")

$path = ".\filename_list.csv"

Import-Csv $path | Foreach-Object { 
  $filename = $_.filename;
  $ext = $docext | Get-Random -Count 1;
  if (!(Test-Path "C:\path\to\files\$filename.*")) {
    $filename | Out-File "C:\path\to\files\$filename.$ext";
    Write-host "creating file $filename";
  } else {
    Write-Host "file already exists";
  }
}

A brief run down.
The @docext is an array of possible extensions, as mine list only has an ID, not the extension. I wanted to make one up for my test.
The $ext = $docext | Get-Random -Count 1; grabs one of these random extensions.
I run a Test-Path to see if the filename exists so it doesn’t create two files with different extensions. I use a wildcard to check.
Lastly I Write-Host so I can see what’s going on.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.