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

时间:2014-03-29 07:11:25

标签: regex windows powershell

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

  

" E:\工作流\ 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 个答案:

答案 0 :(得分:4)

你有一些问题。首先,将 -Recurse 切换到 Get-ChildItem ,这样无论多深,都可以找到匹配过滤器的所有文件。然后,您需要重新创建原始目录结构,因为您无法将文件复制到不存在的目录。 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
}