如何在PowerShell中复制与正则表达式匹配的文件名?

4

我是新手powershell。我需要复制整个目录结构从源到目标,文件名匹配一个模式。我正在做以下事情。但它只会复制根目录中的内容。例如

"E:\Workflow\mydirectory\file_3.30.xml"

不会被复制。

这里是我的命令序列。

PS F:\Tools> $source="E:\Workflow"
PS F:\Tools> $destination="E:\3.30"
PS F:\Tools> $filter = [regex] "3.30.xml"
PS F:\Tools> $bin = Get-ChildItem -Path $source | Where-Object {$_.Name -match $filter}
PS F:\Tools> foreach ($item in $bin) {Copy-Item -Path $item.FullName -Destination $destination}
PS F:\Tools> foreach ($item in $bin) {Copy-Item -Path $item.FullName -Destination $destination -recurse}
1个回答

7

您有几个问题。首先,在Get-ChildItem中添加-Recurse开关,以便找到与过滤器匹配的所有文件,无论有多深。然后,您需要重新创建原始目录结构,因为您无法将文件复制到不存在的目录中。在md上使用-ea 0开关可以确保创建新目录时忽略错误 - 以下操作将解决问题:

$source="E:\Workflow"
$destination="E:\3.30"
$filter = [regex] "3.30.xml"
$bin = Get-ChildItem -Recurse -Path $source | Where-Object {$_.Name -match $filter}
foreach ($item in $bin) {
    $newDir = $item.DirectoryName.replace($source,$destination)
    md $newDir -ea 0
    Copy-Item -Path $item.FullName -Destination $newDir
}

1
我知道这已经是很久之后的事了,但是非常感谢您创建了如此好的教程来指导我们如何做到这一点。 :) - ZaxLofful

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接