Home > Software design >  Powershell: ForEach Copy-Item doesn't rename properly when retrieving data from array
Powershell: ForEach Copy-Item doesn't rename properly when retrieving data from array

Time:08-12

I am pretty new to PowerShell and I need some help. I have a .bat file that I want to copy as many times as there are usernames in my array and then also rename at the same time. This is because the code in the .bat file remains the same, but for it to work on the client PC it has to have the username as a prefix in the filename.

This is the code that I have tried:

$usernames = Import-Csv C:\Users\Admin\Desktop\usernames.csv

$file = Get-ChildItem -Path 'C:\Users\Admin\Desktop\generatedbat\' -Recurse

foreach ($username in $usernames)

{

ForEach-Object {Copy-Item $file.FullName ('C:\Users\Admin\Desktop\generatedbat\'   $username   $File.BaseName   ".bat")}

}

This copies everything and it kind of works but I have one problem.

Instead of having this filename: JohnR-VPNNEW_up.bat

I get this: @{Username=JohnR}-VPNNEW_up.bat

Any help? Thanks!

CodePudding user response:

So you have one .bat file C:\Users\Admin\Desktop\generatedbat\VPNNEW_up.bat you want to copy to the same directory with new names taken from the usernames.csv --> Username column.

Then try

# get an array of just the UserNames column in the csv file
$usernames    = (Import-Csv -Path 'C:\Users\Admin\Desktop\usernames.csv').Username
# get the file as object so you can use its properties
$originalFile = Get-Item -Path 'C:\Users\Admin\Desktop\generatedbat\VPNNEW_up.bat'

foreach ($username in $usernames) {
    $targetFile = Join-Path -Path $originalFile.DirectoryName -ChildPath ('{0}-{1}' -f $username, $originalFile.Name)
    $originalFile | Copy-Item -Destination $targetFile -WhatIf
}

I have added switch -WhatIf so you can first test this out. If what is displayed in the console window looks OK, then remove that -WhatIf safety switch and run the code again so the file is actually copied

  • Related