regex - PowerShell:根据正则表达式值复制/移动文件,保留文件夹结构等

标签 regex powershell web

场景如下:我们有一个生产 Web 服务器,其中包含数千个附加了“_DATE”的文件和文件夹。我们希望将它们移动到临时文件夹(确保它们未被使用),并在稍后删除这些文件。

我可以使用:

Get-ChildItem -Path W:\IIS -Recurse | Where-Object{$_.Name -match "_\d{8,10}$"}

获取所有文件/文件夹及其位置的列表。但手动删除它们似乎需要大量工作,特别是如果将来需要这样做的话。我找到了一些几乎可以满足我要求的示例:

cls

$source = "W:\IIS"
$destination = "C:\Temp\DevTest" 

foreach ($i in Get-ChildItem -Path $source -Recurse)
{
    if ($i.Name -match "_\d{8,10}$")
    {
        Copy-Item -Path $i.FullName -Destination $item.FullName.ToString().Replace($source,$destination).Trim($item.Name)
    }
}

还有:

cls

$source = "W:\IIS"
$destination = "C:\Temp\DevTest" 

$bin = Get-ChildItem -Path $source -Recurse | Where-Object{$_.Name -match "_\d{8,10}$"}

foreach ($item in $bin) {
    Copy-Item -Path $item.FullName -Container -Destination $item.FullName.ToString().Replace($source,$destination).Trim($item.Name) -Recurse
}

这两个问题是,当我仅使用 copy-item 测试它们时,我最终会得到一个平面目录,并且我需要保留目录结构,以便如果移动出错,我可以恢复(最好通过拖动和将所有文件夹放回 IIS 文件夹中),或者我会得到许多额外文件夹/文件的副本,这些文件夹/文件在运行第一个命令时不会出现。

将我的第一个命令修改为:

Get-ChildItem -Path W:\IIS -Recurse | Where-Object{$_.Name -match "_\d{8,10}$"} | Copy-Item -Container -Destination C:\Temp\DevTest -Recurse

将复制我需要的所有内容,但使用平面目录树,而不是保留树结构(但用目标目录替换源目录)。

有什么建议/意见吗?

最佳答案

第一个应该理想地工作。它确实保留了目录结构。但复制文件夹时必须小心。假设您只想要您想要的模式中的文件,并且不关心其中的文件夹,您可以执行以下操作:

$source = "W:\IIS"
$destination = "C:\Temp\DevTest" 

if(-not (Test-Path $destination)) { mkdir $destination | out-null}

foreach ($i in Get-ChildItem -Path $source -Recurse)
{
    if (($i.Name -notmatch "_\d{8,10}$") -and (-not $i.PsIsContainer))
    {
        continue;
    }
    Copy-Item -Path $i.FullName -Destination $i.FullName.Replace($source,$destination).Trim($i.Name)
}

关于regex - PowerShell:根据正则表达式值复制/移动文件,保留文件夹结构等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7893919/

相关文章:

Javascript正则表达式重复行匹配无法正常工作

node.js - nodejs Express 正则表达式路径 : working in test, 在代码中不起作用。我做错了什么?

javascript - 将 Javascript Replace() 函数移植到 Objective C

sharepoint - PowerShell SharePoint 数据表

powershell - 如何将 powershell UTC 日期时间对象转换为 EST

javascript - 是否有允许在所有三种浏览器(IE、FF、Chrome)中进行调试的 JavaScript IDE?

javascript - 使用 div 的高度来确定另一个 div 的 padding 或 margin-top

c# - 帮助对 C# 中的文本字符串进行正则表达式验证

networking - 在 PowerShell 中检查网络服务器上的 IP 地址开关的好方法是什么?

web - 我想将我的网站与App Store集成在一起,让客户通过App Store付款