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'.
1
  • 1
    Create the destination folder in $fulldst first Commented Mar 27, 2021 at 15:03

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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 It is preferable to Out-Null, because it is much faster. See measurements here: stackoverflow.com/a/5263780/7571258

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.