Improve company productivity with a Business Account.Sign Up

  • Status: Solved
  • Priority: High
  • Security: Private
  • Views: 59
  • Last Modified:

Simple ForEach Loop in Powershell

Having a brain fart right now -- I have a simple PowerShell script running a ForEach loop. Please see below:

# Define list of servers
$Servers = Get-Content C:\computersFile.txt

foreach ($Computer in $Servers) 
        # Create a backup of current file 
        Copy-Item "\\$remoteHost\$source" -Destination "\\$remoteHost\$destination"

Open in new window

$remoteHost is a placeholder just to show what I am trying to do .. I'd like to use the computer names in the computersFile.txt to specify my path like such "\\compuerName\C:\Program Files"

How could I dynamically populate that path ? If I use "$Computer" it attempts to put the entire txt file into that path.

I know I've done this before but for some reason cannot remember.

Any help is much appreciated.
  • 2
  • 2
3 Solutions
rastoiWindows DTS expertCommented:
in such loop every $Computer should contain one line from computersFile.txt
how is your source file formatted ?
SysAdminAuthor Commented:
That's what I thought .. it is a simple .txt file with computer name 1 per line like this:


Open in new window

Maybe I should use a .csv file instead?
rastoiWindows DTS expertCommented:
Ok. Just to valide run it such sample like you post here with write-host indtead of copy-item to see result
Shaun VermaakTechnical Specialist/DeveloperCommented:
Add this command to line 6 and post results. I expect you need to use $Computer.WhatEverIsInLine1

Open in new window

SysAdminAuthor Commented:
Hey everyone thanks for the help -- here's what's really odd I just recreated the TXT file and placed it in a different directory and it's working as it should -- I thought I was crazy but I'm not!

Thanks for all your help. If I have any other issues I'll be sure to come back!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now