Uncategorized · March 22, 2021 0

Reading a list of computers from text file

Welcome to Powermator,

In this thread I will show you how to read list of computers from a text file and store it in an array so you can easily loop through that array and do your task. Before we start lets assume you have a text file under C drive in a folder called temp; and within the text there are bunch of computer names as seen below

to import the list into an array we need to use the PowerShell command Get-Content the code looks like below

[string[]]$arrayFromFile = Get-Content -Path 'c:\temp\computers.txt'

Now, if you want to loop through the computers, simple use foreach

foreach($item in $arrayFromFile)
{
write-host $item
}

if you run the above code; it should looks like

as you see above we have computers that are duplicated and you might want to eliminate any duplication within your loop. To do that simply use the below code before the loop

$arrayFromFile = $arrayFromFile | sort -unique

thus the whole code would looks like below

cls
[string[]]$arrayFromFile = Get-Content -Path 'c:\temp\computers.txt'
$arrayFromFile = $arrayFromFile | sort -unique #remove duplication and make unique values

foreach($item in $arrayFromFile)
{
write-host $item
}

Feel free to use the code on your own risk.

cheers

Jaber

Close Bitnami banner
Bitnami