user1616756
user1616756

Reputation: 13

Read in two text file lists and write out 1 line from to a text file

I need to create a powershell script that reads in two text files with lists. The first list is used to identify the remote computers that will have a file appended to it. The second list is the key phrase that needs to be appended to the file.

List 1: Computer1 Computer2 Computer3

List 2: ABC DEF GHI

Script would loop through each pointing to a file say C:\temp\help.txt on each of the remote computers and write 1 line from List 2.

So Example: When the script runs it goes out to List 1, finds that computer 1 is first and opens the file \computer1\C$\temp\help.txt, it would then grab the first line from List 2 and write to the file ABC. Close the file and go on to Computer 2. Computer 2 would be \computer2\C$\temp\help.txt and would grab the 2nd item from List 2 and write to it DEF save and move on.

It's been hard to find any help reading in and looping through 2 lists. Or perhaps I am thinking of it wrong. I have gotten to Get-Content to read in the file and foreach($x for text1) can go through 1 of the text files loops but can not figure out how to loop through the 2nd text file.

Upvotes: 1

Views: 186

Answers (1)

latkin
latkin

Reputation: 16792

Processing side-by-side arrays is always a pain, and tends to be error prone. Ideally, as suggested, the computer names and strings would be together in a CSV or something.

But as is, something like this should get you on the right track. You might have to fiddle with newlines at the beginning/end of the strings a bit.

$machines = Get-Content .\MachineList.txt
$strings = Get-Content .\StringsList.txt

if($machines.Count -ne $strings.Count){ throw 'Counts do not match' }

for($i = 0; $i -lt $strings.Count; $i++)
{
  $path = "\\$($machines[$i])\C`$\temp\help.txt"   # unc path
  $strings[$i] | Add-Content $path
}

If you have it in a CSV like

Config.csv
---------
ComputerName,String
machine1,string1
machine2,string2
machine3,string3

Then you could simplify to this:

Import-Csv .\Config.csv |%{
  $_.String | Add-Content "\\$($_.ComputerName)\C`$\temp\help.txt"
}

Upvotes: 3

Related Questions