代码之家  ›  专栏  ›  技术社区  ›  Brandon

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

  •  0
  • Brandon  · 技术社区  · 8 年前

    问题

    我想递归搜索一个目录,只要文件夹名称与对象的父目录匹配,就将对象的副本粘贴到该文件夹中,覆盖与该对象共享名称的任何文件。

    $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\*"
        }
    }
    

    问题

    2 回复  |  直到 8 年前
        1
  •  1
  •   Ansgar Wiechers    8 年前

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

    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
    }
    
        2
  •  0
  •   Paolis    8 年前

    理想情况下,在处理任何项目组(在本例中为网站)时,尝试为项目找到唯一标识符。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 
    }