Reading files in a folder and creating a file with the file names

Imagine you need to get the list of file names in a folder to a csv file or a flat file. Sounds simple right? Yes it is, but what if the folder contains 100’s of files. Well it’s not that simple.

And what if you don’t want the entire filename, instead need to read the characters before a ‘-‘ and also needs to pad some spaces or zero’s on each line. Well PowerShell comes to our rescue in this case.

First step is to get the list of file names into an array.

 $files = (Get-ChildItem -Path \\192.168.0.10\ToBeLoadedPics -Filter *.jpg) 

The Get-ChildItem cmdlet gets all the items in the folder. You can give a -Filter parameter to specify any specific file type.

Next step is to loop through this array $files and populate each line you need into an array.

$result = @();
for($i=0;$i -lt $files.Count;$i++)
{
  $file = $files[$i]
  $row = $file.Name.Substring(0,$file.Name.IndexOf("-"));
  $outline = "00${row} ,${file}".PadRight(94,' ');
  $result += $outline;
}

So now we have the result in the array $result. We need to write it to a csv file  or a text or any kind of file as you like. We can achieve that by using Out-File cmdlet.

$result | Out-File \\192.168.0.10\Output\LoadedPics.csv

 

Leave a comment