Skip to main content

Command Palette

Search for a command to run...

Powershell Script: Get-ChildItem

Demonstrating the use of the PS cmdlet: Get-ChildItem

Updated
2 min read
Powershell Script: Get-ChildItem
J

Disciple of Jesus, husband, and father.

Job: Full Stack Developer/Architect Interests: Technology and football

In this article, I want to demonstrate the use of the PowerShell cmdlet: Get-ChildItem.

Let's consider this scenario.

Imagine you need to get the list of file names in a folder to a CSV or 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, read the characters before a ‘-‘ and pad some spaces or zero’s on each line. Well, PowerShell comes to our rescue in this case.

Reading files in a folder and exporting it to a file using Powershell scripts

  • The first step is to get the list of file names into an array.
$files = (Get-ChildItem -Path \192.168.0.10\ToBeLoadedPics -Filter *.jpg)
Get-ChildItem
The Get-ChildItem cmdlet gets all the items in the folder. You can give a -Filter parameter to specify any specific file type.
  • The 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 can write it to a CSV file, text, or any file you like. We can achieve that by using the Out-File cmdlet.
$result | Out-File \192.168.0.10\Output\LoadedPics.csv

All other tech

Part 1 of 1

This series is where I will be publishing all other tech articles that can't be categorized