Powershell Foreach Loop with Variable for User Accounts to Copy File

I'm trying to copy a file to a list of users' folders on a network share using a foreach loop and a variable containing all of the user names. This is what I've done so far with no success. I understand why it's not working (loading all usernames at once in the variable), but I'm not sure what to do to correct it, or if a foreach loop is the best route to take. I've tried a lot of variations of the below and done a lot of googling.

$whusers = "username1", "username2", "username3"

Foreach ($user in $whusers) {
xcopy "C:\users\myname\desktop\shortcut.url" "F:\corp users\$whusers\desktop" }

Any help would be great appreciated!

2 Answers

When using a ForEach loop, you are iterating through all elements of the 2nd variable and putting them in turn into the first. Inside the ForEach, you must reference the first variable, not the second. Change the $whusers inside your ForEach to $user$.

Try this:

$whusers = "username1","username2","username3"

Foreach ($user in $whusers) {
    xcopy "C:\users\myname\desktop\shortcut.url" "F:\corp users\$user\desktop"
}
1

Even this can done withou using the $user variable. ForEach is used to iterate over an array. If the object to iterate over is piped as input, there is a special variable $_ to act as each time as the element of an array.

$whusers = "username1", "username2", "username3"

$whusers | ForEach {
xcopy "C:\users\myname\desktop\shortcut.url" "F:\corp users\$_\desktop" 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest