Powershell foreach statement not working

powershell

I have this foreach statement that goes through a list of usernames and puts each name in the path listed below, then it copies and pastes a file to the individual users startup folder. For some reason i get an error that a portion of the path was not found. Any ideas what the problem could be?

#for each username folder copy the a file to the users startup folder
foreach ($_ in $usernames)
{
$destination = "C:\users\"+ "$_" + "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
Copy-Item -Path c:\temp\file.bat -destination $destination -force
}

I have tried changing the way the path for my $destination variable is written and i get the same results

Best Answer

A couple of issues with this:

1) foreach ($_ in $usernames). Its really bad practise to try and inject into a pipeline variable and can be unpredictable at best. Instead try something like ForEach($username in $usernames)

2) your string build for $destination could do with better formatting. try something like $destination = "'C:\users\$username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup'"

3) Indentation - makes it easier to read

Putting it all together - you get something like:

foreach ($username in $usernames)
{
    $destination = "'C:\users\$username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup'"
    Copy-Item -Path c:\temp\file.bat -destination $destination -force
}

For extra points:

  • put the file you're copying into a variable for easier modifications or reuse

  • look to add an error handler and make sure the path exists before you try the copy

You then end up with something that looks like this:

$sourceFile = "C:\temp\file.bat"
foreach ($username in $usernames)
{
    $destination = "'C:\users\$username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup'"
    if (Test-Path $destination) {
        try {
            Copy-Item -Path $sourceFile -destination $destination -force
            Write-Host "Copy Completed"
        } catch {
            Write-Host "Copy to $destination Failed"
        }

    } else {
        Write-Host "$destination Does Not Exist"
    }
}

You'll now be told if each copy succeeds, fails because the path doesnt exist or fails because the copy fails (access denied or similar)

Related Topic