My favorite is to use the .Net class [IO.DirectoryInfo], which takes care of some logic. I really use this for many similar scripting tasks. It has a .Create () method, which creates directories that do not exist, without errors, if they do.
Since this is still a two-step problem, I use the foreach alias to make it simple. For individual files:
[IO.DirectoryInfo]$to |% {$_.create(); cp $from $_}
As for your file with multiple files / directories, I would use RoboCopy over xcopy. Remove the "*" from yours and just use:
RoboCopy.exe $from $to *
You can still add / r (Recurse), / e (Recurse, including Empty), as well as 50 other useful switches.
Edit: Looking back at this, it's concise, but not very readable unless you often use code. I usually broke it into two parts, for example:
([IO.DirectoryInfo]$to).Create() cp $from $to
In addition, DirectoryInfo is a type of the parent property of FileInfo, so if your $ to is a file, you can use them together:
([IO.FileInfo]$to).Parent.Create() cp $from $to
Michael Erickson Sep 09 '16 at 14:27 2016-09-09 14:27
source share