将文件移动到父文件夹名称匹配的新位置

时间:2017-08-23 13:49:21

标签: powershell rollback copy-item

问题

我正在我的应用程序中处理回滚功能,我将文件从备份/回滚目录复制到目标文件夹。听起来很简单,这就是它变得复杂的地方。由于所有文件共享相同或相似的名称,我使用父文件夹作为锚点来帮助强制执行唯一的位置。

我想基本上递归搜索目录,并且文件夹名称与对象的父目录匹配,将对象的副本粘贴到该文件夹​​中,覆盖与所述对象共享名称的任何文件。

更明显的表示方式是:

$Path = C:\Temp\MyBackups\Backup_03-14-2017
$destination = C:\SomeDirectory\Subfolder
$backups = GCI -Path "$Path\*.config" -Recursive

foreach ($backup in $backups) {
    Copy-Item -Path $backup -Destination $destination | Where-Object {
        ((Get-Item $backup).Directory.Name) -match "$destination\*"
    }
}

然而,上述情况不起作用,我的研究都没有发现任何类似于我正在做的事情。

问题

是否有人知道如何将项目从一个位置复制到另一个位置,其中复制项目的父文件夹与使用PowerShell的目标文件夹匹配?

2 个答案:

答案 0 :(得分:1)

枚举备份文件,将源基本路径替换为目标基本路径,然后移动文件。如果您只想替换现有文件,请测试目标是否存在:

Get-ChildItem -Path $Path -Filter '*.config' -Recursive | ForEach-Object {
    $dst = $_.FullName.Replace($Path, $destination)
    if (Test-Path -LiteralPath $dst) {
        Copy-Item -Path $_.FullName -Destination $dst -Force
    }
}

如果要恢复目标中缺少的文件,请确保首先创建缺少的目录:

Get-ChildItem -Path $Path -Filter '*.config' -Recursive | ForEach-Object {
    $dst = $_.FullName.Replace($Path, $destination)
    $dir = [IO.Path]::GetDirectoryName($dst)
    if (-not (Test-Path -LiteralPath $dir -PathType Container)) {
        New-Item -Type Directory -Path $dir | Out-Null
    }
    Copy-Item -Path $_.FullName -Destination $dst -Force
}

答案 1 :(得分:0)

你可能在想这个。如果您要从网站备份web.config文件,我强烈建议您使用SiteID作为备份文件夹。然后,只需使用此方法找到正确的文件夹,以便将web.config文件复制到要回滚的时间。

理想情况下,在处理任何项目组(在此实例中为网站)时,请尝试查找项目的唯一标识符。 SiteID是理想的选择。

$Path = C:\Temp\MyBackups\Backup_03-14-2017  #In this directory store the web.config's in directories that match the SiteID of the site they belong to
#For example, if the site id was 5, then the full backup directory would be: C:\Temp\MyBackups\Backup_03-14-2017\5 
$backups = Get-ChildItem -Path $Path -Include *.config -Recurse

foreach ($backup in $backups) 
{
    $backupId = $backup.Directory.Name
    $destination = (Get-Website | where {$_.id -eq $backupId}).physicalPath

    Copy-Item -Path $backup -Destination $destination 
}
相关问题