I'm attempting to copy selected contents of a folder on my workstation to a network share.
Workstation's folder:
\ProjectX
DocumentA.sql
DocumentA.ad
\Build
DocumentA.csv
I'd like to copy the contents of ProjectX to \\server\shared\projects\ProjectX (the ProjectX folder has already been created).
The desired result:
\ProjectX
DocumentA.sql
\Build
DocumentA.csv
I've tried:
$destination = '\\server\shared\projects\ProjectX'
Get-ChildItem '.\*' -Include '*.csv', '*.sql' -Recurse | Foreach {
Copy-Item -Path $_ -Destination $destination -Recurse
}
Unfortunately, this results in:
\ProjectX
DocumentA.sql
DocumentA.csv
What am I missing?
I'm not interested in an answer involving robocopy.
It's a pain because Copy-Item is too stupid to do the job right. That means you have to program the logic yourself.
Usually I end up with something like this:
$Source = (Get-Location).Path;
$Destination = '\\server\shared\projects\ProjectX';
Get-ChildItem -Path $Source -Include '*.csv','*.sql' -Recurse | ForEach-Object {
# Get the destination file's full name
$FileDestination = $_.FullName.Replace($Source,$Destination);
# Get the destination file's parent folder
$FileDestinationFolder = Split-Path $FileDestination -Parent;
#Create the destination file's parent folder if it doesn't exist
if (!(Test-Path -Path $FileDestinationFolder)) {
New-Item -ItemType Directory -Path $FileDestinationFolder | Out-Null;
}
# Copy the file
Copy-Item -Path $_.FullName -Destination $FileDestination;
}
Edit: I think this will fail when you try to create a subdirectory when the parent directly doesn't exist. I'll leave that as an exercise for the reader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With