0

I want Copy-Item to copy to the destination file and create any subfolders on the way, but I can't seem to get that to work.

Copy-Item $fullsrc $fulldst -Recurse -Force -Verbose

$fullsrc and $fulldst are full paths with filenames as the destination filename is different from the source filename. Is there a way to get Copy-Item to create the subfolders and then copy the file over?

VERBOSE: Performing the operation "Copy File" on target "Item: D:\mypath\logs\001.123.log
Destination: D:\newpath\newlogs\123.234.log".
Copy-Item : Could not find a part of the path 'D:\newpath\newlogs\123.234.log'.
YorSubs
  • 3,194
  • 7
  • 37
  • 60

2 Answers2

1

Copy-item have't function to create a folder, you need to previously create it

 Copy-Item $fullsrc $(new-item -ItemType Directory -Path $fulldst) -Recurse -Force -Verbose -ErrorAction SilentlyContinue
FletcherF1
  • 167
  • 7
1

You have to create the parent directory of the destination file on your own.

# Split-Path with single parameter outputs the parent directory
$null = New-Item (Split-Path $fulldst) -ItemType Directory

Copy-Item $fullsrc $fulldst -Force -Verbose

Note that -Recurse switch has no use when you specify full source and destination file paths, so I've removed it.

zett42
  • 25,437
  • 3
  • 35
  • 72
  • I was pretty sure that `-Recurse` did nothing, but was just trying anything to see if it would work. I've not seen `$null = ` used in this way. Is this preferable to `| Out-Null`, or are they essentially identical constructs? – YorSubs Mar 28 '21 at 02:48
  • 1
    @YorSubs It is preferable to `Out-Null`, because it is much faster. See measurements here: https://stackoverflow.com/a/5263780/7571258 – zett42 Mar 28 '21 at 08:24