October 6, 2022

Samir Daoudi's Technical Blog

SharePoint, Office 365, C#, .Net, SQL Server News, Tips, Ebooks, Events, Webinars ….etc

PowerShell (Part 2) – Feeding files

In Today’s article we will have a look at how you can read data from the two main filetypes you can feed your PowerShell Script.

1- From a TXT file

A text file is useful if you want to provide a list of entries, each row will contain one piece of information, I will say, that this is the simplest and easiest way to feed information to your .PS1 script.

Let’s suppose we have a list of items file called “ListItems.txt“, which will look like this:

Your code which will loop over each line and output the result will look like this:

$List= Get-Content ListItems.txt
foreach ($item in $List) {
    Write-Host $item
}

 

When we run this script :

2- From a CSV file

If you want to have multiple information in your input files (example a list of products), you can use a CSV file.

My input file “listitems.csv” look like this:

And the script to read each line and output each column will be :

$List= Import-CSV ListItems.csv
foreach ($item in $List) {
    Write-Host $item.Product
    Write-Host $item.Description
    Write-Host $item.Price
    Write-Host "------------"
}

Please note that we can use the column name as a property of the $item (which is the line ref in our scenario)

Leave a comment

You may have missed

Show Buttons
Hide Buttons

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

%d bloggers like this: