简体   繁体   中英

Read text file and run a copy command for each line in the text file

I am trying to write a Powershell script that will read a text file on my desktop that is filled with user names, then go out to a specified folder on our network share, lets say u:\\data and copy the contents from that folder to another network share lets says y:\\information , for each user in the text file.

How would this be written?

I have tried several things with reading the text file then trying several commands to copy and paste but they each failed.

UPDATE:

Below is what I have done so far:

$user = Get-Content "test.txt"

$path = "\\abnas2\abusers\users"

$path2 = "\\abnas2\abdept\dept\testcopy"

$Copy = Copy-Item -path $path\$user\ * -Destination $path2\$user

I had one username in the test.txt file called user1 and it pulled the name, and copied perfectly.

Now if I add more than one name to the test.txt file and run the above, it errors out. The error it returned made it look like the 3 user names in the list were one user name.

What I need this to do is run the command for each name on the list. I was thinking I could use the foreach command But not sure how to do it.

UPDATE - 04\\09\\2014: I have tried the following and am getting an error back: $user = Get-Content "test.txt" $path = "\\abnas2\\abusers\\users" $path2 = "\\abnas2\\abdept\\dept\\testcopy" $Copy = Copy-Item -path $path\\$user* -Destination $path2\\$user foreach($username in $user) { Copy-Item -path $path\\$username* -Destination $path2\\$username\\ }

When I run it I am getting the following error: Copy-Item : An object at the specified path \\\\abnas2\\abusers\\users\\user1 user2 user3 does not exist.

These are the names in my test.txt file, is there a way to get it to read one line at a time and execute the copy and when done go to the next name on the list and do the same? I'm not sure how to get it to do that.

You can use foreach

In this case:

foreach($username in $user) {
   Copy-Item -path $path\$username\* -Destination $path2\$username\
}

would copy the contents of each named folder in $user under $path to its corresponding folder in $path2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM