How do I copy a file more than once to a folder using the same line of code?
I have this code here:
$TodayDate = Get-Date -Format "dd-MM-yyyy"
$TodayDateSecs = Get-Date -Format "dd-MM-yyyy I hh-mm-ss"
$Sheet01 = "C:\Users\MyUser\Desktop\Sheets"
$Sheet01exists = get-ChildItem $Sheet01 -recurse | where {$_.name -match "Modelo 01 - $TodayDate"} | select name
$Project01 = "C:\Users\MyUser\Desktop\Project 01\Model 01.txt"
$WatchFolder = "C:\Users\MyUser\Desktop\Watch Folder\$ClientName"
$OldSheets = "C:\Users\MyUser\Desktop\Project 01\Old Sheets"
$MoveSheetAfterRender = get-ChildItem $Sheet01 -recurse | where {$_.name -match "Modelo 01 - $TodayDate"} | Move-Item -Destination $OldSheets
If ($Sheet01exists) {
Copy-Item -Path $Project01 -Destination "$WatchFolder\Model 01 - $TodayDateSecs.txt"
$MoveSheetAfterRender
Write-Host "Copiado para Renderização"
}
Else {
Write-Host "Arquivo não encontrado"
}
My intention is: every time $Sheet01exists
returns a match I would like the file specified in $Project01
to be copied to a folder in $WatchFolder
.
The problem is that if there is more than one file corresponding to $Sheet01exists
the file from $Project01
will only be copied once.
What I need is for the file in $Project01
to be copied to $WatchFolder
for each match in $Sheet01exists
. That is, it needs to be copied and renamed in order not to be overwritten.
How can I do this as cleanly as possible?
CodePudding user response:
Here's one way to go about it piping directly to a Foreach-Object
loop:
$TodayDate = Get-Date -Format "dd-MM-yyyy"
$TodayDateSecs = Get-Date -Format "dd-MM-yyyy I hh-mm-ss"
[ref]$i = 0
$Project01 = "C:\Users\MyUser\Desktop\Project 01\Model 01.txt"
$WatchFolder = "C:\Users\MyUser\Desktop\Watch Folder\$ClientName"
$OldSheets = "C:\Users\MyUser\Desktop\Project 01\Old Sheets"
$Sheet01 = "C:\Users\MyUser\Desktop\Sheets"
Get-ChildItem -Path $Sheet01 -Filter "*Modelo 01 - $TodayDate*" -Recurse |
ForEach-Object -Process `
{
Copy-Item -Path $Project01 -Destination {
'{0}\Model 01 - {1}{2}.txt' -f $WatchFolder, $TodayDateSecs,
$(
if ($i -ne 0)
{
'[{0:D2}]' -f $i
}
$i
)
} -Verbose -WhatIf
Move-Item -Path $_.FullName -Destination $OldSheets -WhatIf
}
Since you're just moving the same files found out of their location onto $OldSheets
, you can do it inside the loop by passing it the objects path. As for the files that are to be copied over, since -Destination
accepts a scriptblock you can create a string of your own with incrementing $i
, then appending it to the end of the path giving you the [01]..[10]
effect.
Remove the -WhatIf
safety/common parameter when you've dictated those are the results you're after.