如何复制具有文件夹结构的项目?

How to copy-item with folder structure?

这是我的代码:

$path 是一个包含我要复制的完整文件路径的数组。

$path 

Y:000[=10=]000001.TIF
Y:000[=10=]000002.TIF
Y:000[=10=]000004.TIF

for ($i = 0; $i -lt $path.count; $i++)
{ 
Copy-Item -Recurse -Path $path[$i] -Destination "D:\myfiles"
}

它有效,但它直接将我的文件复制到 D:\myfiles 文件夹的根目录下,我想将我的文件复制到它们各自的文件夹中。他们已经存在。

这是我得到的:

D:\myfiles[=11=]000001.TIF
D:\myfiles[=11=]000002.TIF
D:\myfiles[=11=]000003.TIF

这就是我想要的:

D:\myfiles000[=12=]000001.TIF
D:\myfiles000[=12=]000002.TIF
D:\myfiles000[=12=]000003.TIF

如何实现?

谢谢

这就是我的做法,在评论中解释,希望能理解:)

如果您需要该功能,此方法应该能够处理网络路径。

$path =
@(
    'Y:000[=10=]000001.TIF'
    'Y:000[=10=]000002.TIF'
    'Y:000[=10=]000004.TIF'
)

for ($i = 0; $i -lt $path.count; $i++)
{
    # Change this for additional directories
    $sourceFolder = 'D:\myfiles'

    # Get the old path and split on a semi colon
    # Where-Object to filter out empty strings / null entries
    $sourceFile = $path[$i] -Split "\" | Where-Object -FilterScript {$_}

    # Join the path we split to our destination
    # 1 is the 2nd item in the index (0 is the first)
    # $source.count - 2 will get the second last item in the index
    # (-2 because we're taking off the first and last)
    #
    #    [0]         [1]                [2]
    #    Y:    \    15000     \      00000004.TIF
    #
    # Once done, join all the parts back together with -Join '\'
    $destination = Join-Path -Path $sourceFolder -ChildPath ($sourceFile[1..($sourceFile.count - 2)] -Join "\")

    # Copy files to the destination we calculated
    # Don't need -Recurse if we're giving full paths but up to you
    Copy-Item -Recurse -Path $path[$i] -Destination $destination
}

如果您提到的目标父文件夹已经存在,那么您可以这样做:

$paths = 'Y:000[=10=]000001.TIF', 'Y:000[=10=]000002.TIF', 'Y:000[=10=]000004.TIF'

foreach ($item in Get-Item $paths)
{  
    Copy-Item -Path $item.FullName -Destination "D:\myfiles$($item.Directory.Name)"
}

请注意在 -Destination 字符串中使用变量扩展 $($item.Directory.Name) 来标识父文件夹。