用于备份和替换文件的Powershell脚本

时间:2013-05-13 02:37:22

标签: powershell powershell-v3.0

我正在开发项目,如果目标上已存在相同的文件,则部署工具会自动添加“.update”扩展名。 e.g。

root
    web.config
    web.config.update
    connection.config
    connection.config.update

我想通过powershell执行以下后期部署:

  1. 备份* .config。
  2. 用* .update文件替换现有的* .config。 以下是所需的输出:

    根         web.config中         web.config.update         CONNECTION.CONFIG         connection.config.update     根         web.config中         CONNECTION.CONFIG         备用             web.config中                 CONNECTION.CONFIG

  3. 有人可以帮助使用PowerShell来实现上述目标吗?

1 个答案:

答案 0 :(得分:4)

以下代码可以执行您想要的操作。

  1. 将现有配置文件备份到基于的命名备份文件夹 当前日期。
  2. 通过删除现有配置文件并重命名更新文件来替换现有配置文件。

    $root_folder = 'c:\temp\root'
    
    # Create a backup folder 
    $backup_directory = New-Item -Path "$root_folder\backup_$(Get-Date -Format yyyyMMdd)" -Force -ItemType Directory
    
    Get-ChildItem -Filter *.config | ForEach-Object {
    
        # Copy .config files to the backup directory
        Copy-Item -Path $_.FullName -Destination "$($backup_directory.Fullname)" -Force
    
        # Delete the file from the source directory
        $_ | Remove-Item
    
        # Rename the .update files to .config files.
        Rename-Item -Path "$($_.FullName).update" -NewName $_.FullName -Force
    }
    
相关问题