how to copy an item which is in the newest folder in one directory to another
By Emily Wilson •
I am trying to copy a file from the newest folder in on directory to another folder. I have made the code below but it seems that the copy-item command does not work with variables. Does anyone have any other ideas?
# Code to get newest directory
$newestFolder = gci \\Server123\sharepoint\HCL\HCL-SUPPORT-SHARED\REPORTING\CAPACITY-PLANNING\ | ? { $_.PSIsContainer } | sort CreationTime -desc | select -f 1
<# get the latest created folder from a path #>
# Copy folder to a folder with different name
Copy-Item $newestFolder.FullName -Destination "\\Server123\sharepoint\HCL\HCL-SUPPORT-SHARED\REPORTING\CAPACITY-PLANNING\SP Capacity Planning" -RecurseError Message:
Copy-Item : Cannot find path '\\Server123\sharepoint\HCL\HCL-SUPPORT-SHARED\REPORTING\CAPACITY-PLANNING\SP Capacity Planning\Average-Action.csv' because it does not exist. At line:26 char:1 + Copy-Item -Path $sourcedirectory\Average-Action.csv -Destination $tar ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (\\Server123...rage-Action.csv:String) [Copy-Item], ItemNo tFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand Copy-Item : Cannot find path '\Server123\sharepoint\HCL\HCL-SUPPORT-SHARED\REPORTING\CAPACITY-PLANNING\S P Capacity Planning\MaxDuration20.csv' because it does not exist. At line:47 char:1 + Copy-Item -Path $sourcedirectory1\MaxDuration20.csv -Destination $tar ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
31 Answer
Double-check that you are actually copying a directory to a directory, because the error you posted is using a file name instead of a folder.
Try the following using your paths:
$sourcefolder = '\\path\to\folder\'
$targetfolder = '\\path\to\target\'
$newestfolder = gci -Directory $sourcefolder | sort CreationTime -desc | select -f 1 ## get the newest folder
copy -recurse $newestfolder $targetfolder 5