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

标签 regex windows powershell

我是 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}

最佳答案

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

$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
}

关于regex - 如何在 powershell 中复制与正则表达式匹配的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22728174/

相关文章:

azure - Powershell - 在模块中找到命令,但无法加载模块

python - 匹配不包含特定字符串的文件

c# - Windows 服务器 2008 : Is opening smtp port not enough for sending mail?

windows - edb 数据库中的事务日志文件

excel - 如何使用 PowerShell 将 VBA 代码添加到 Excel 工作表?

.net - 在PowerShell中仅使用WinSCP下载新文件

javascript - 用于匹配 32 个字符的混合字符字符串的正则表达式

python - 使用python正则表达式查找重复表达式

javascript - String#match() 捕获组的奇怪行为

Java - 获取用户的名字和姓氏