Reading data from a file in PowerShell

 

 

This post is about getting data from an array, file, or csv and cycling it through a PowerShell script.

However you get the data you need to store it into a variable. For this demo I am using the variable $items.

To cycle through items one by one you need a foreach loop.

This takes the following form:

foreach ($variable in $list){

#do something

}

Here is an example

$computers = @(“DC01″,”w8p”,”member01″)

foreach ($computer in $computers){
Test-Connection -ComputerName $computer -Quiet
}

The script goes through the array and tests whether it can ping the hosts one by one. If it can it returns turn is not it returns false

First you need to put your list into a variable. There are a number of ways of doing this.

Get-content can be used to read the content of a file. $A = Get-content -path “C:\temp\list.txt”

Import-Csv inputs the content of a csv comma separated value (can be created with excel). $a = Import-Csv -Path “C:\Temp\file.csv”

You can use an array like I did in the last example  $A = @{“value1″,”value2″,”etc”}

Finally you can use the contents of a get command like $A = Get-ADComputer -Filter *

When you collect objects as opposed to text in the foreach statement you would use something like:

foreach ($item.name in $items){}

here is an example of importing a CSV into a variable and running a simple out-host on it.

15

I have created a simple csv called shapes.csv

$shapes = Import-Csv -Path “C:\Temp\shapes.csv”

foreach ($shape in $shapes)
{
Write-Host $shape.name $shape.colour $shape.sides
}

you can see how the first line of each column becomes the header and the name of the property.

I am going show the same example with a text file.

16

I have made a list called items.txt

If you need to you can copy the content of any get command and paste it to notepad. It may not be the best way of scripting but it works in a pinch.

$items = Get-Content -Path C:\Temp\items.txt

foreach ($item in $items){
Write-Host $item
}

PS C:\WINDOWS\system32> $items = Get-Content -Path C:\Temp\items.txt

foreach ($item in $items){
Write-Host $item
}
square
box
table
graph
chair
speaker
cup