【问题标题】:Powershell script to deploy files with necessary backup用于部署具有必要备份的文件的 Powershell 脚本
【发布时间】:2015-03-18 04:35:07
【问题描述】:

团队, 我正在编写一个 powershell 脚本来自动化我们每天执行的一项手动任务。我需要专家建议和帮助,因为我是 powershell 脚本的新手。

要求:

有一个源、目标和一个备份文件夹。

源可能有差异文件和源的多个文件夹中的文件。

例如:source\Login.aspx 或 source\App_Code\BLogic.vb 或 source\bin\servr.dll 等。

复制到destination时,必须检查我的source文件是否存在于destination,如果存在则我们需要复制destination中的当前现有文件 到 backup 文件夹,然后将 source 复制到 destination。

以下是我到目前为止尝试过的脚本。

脚本1:

我能够列出相同但无法将这些数组元素复制到备份位置的文件:

#Declare Source and Destination
$source = Get-ChildItem -Recurse -path \\server1\\e$\ps\src\
$dest = Get-ChildItem -Recurse -path \\server2\\e$\ps\dest\
#lists only objects which are equal and assign to variable
$files=compare-Object -DifferenceObject $source -ReferenceObject $dest -IncludeEqual -ExcludeDifferent
$array = @($files)
$len=$array.length
for ($i=0; $i -lt $array.length; $i++) 
{
 $array[$i]
}

脚本2:

由于 script1 我遇到了问题,我用这个脚本尝试了一个愚蠢的逻辑,但我觉得这也有太多的手工工作:(请帮助我。

Function cpytest ($s, $d)
{
Copy-Item -Path $s -Destination $d;
}
$n = Read-Host "Enter no of files to be uploaded"
$b = Read-Host "Enter Backup Location for file backups"
for ($i=0;$i -lt $n;$i++)
  {
   $s = Read-Host "Enter Source with complete file name"
   $d = Read-Host "Enter Destination with file name too"
   $r = Test-Path $d
   If ($r -eq "True")
   { 
    cpytest $d $b
    cpytest $s $d
    }
   Else
   {
   cpytest $s $d
    }
 }

【问题讨论】:

  • 为什么不直接将整个目录复制到备份位置,然后用新版本覆盖?
  • 我们需要为所有文件版本保留 1 个月的备份,这是开发团队的要求。
  • 另外,一些应用逻辑还包括在应用文件夹中上传文档,这些文档超过 GB 或 GB+,因此保留另一个副本会占用空间。
  • 您的开发团队应该拥有版本控制中的所有内容并记录何时部署的内容 - 并且能够随时从这些来源重新创建任何状态。备份对您的灾难恢复计划有好处,但听起来您正在对其他地方已经存在的东西进行备份。

标签: powershell automation powershell-2.0


【解决方案1】:

试试这样的:

Function BackupAndMoveFile($filePath, $backupPath, $deployPath) {

    $fileName = Split-Path $filePath -Leaf

    $deployFile = Join-Path $deployPath $fileName

    if ((Test-Path $deployFile)) {
        $backupFile = Join-Path $backupPath $fileName
        Move-Item $deployFile $backupFile -Force
        if (!(Test-Path $backupFile)) {
            Write-Warning "Can't backup $fileName to $backupFile"
            return $false
        }
    }

    Copy-Item $filePath $deployPath -Force
    if (!(Test-Path $deployPath)) {
        Write-Warning "Can't deploy $fileName to $deployPath"
        return $false
    }

    return $true
}


BackupAndMoveFile 'C:\temp\backup-test.txt' `
                  'C:\temp\backup' `
                  'C:\temp\deploy'

它将覆盖备份目录中的任何内容,因此您可能需要修改以添加时间戳。

【讨论】:

  • 非常感谢脚本。这对于单个文件非常有用。我可以通过一次函数调用获得逻辑或示例代码来执行多个文件复制吗?我正在尝试将其放入 for 循环中,但如果我的应用程序有 100 个文件要移动,那么它很难多次调用函数..
猜你喜欢
  • 2013-02-26
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多