Powershell 3 - 实例: 备份 Jenkins server 文件

Write-Host ("~~~~~~~~~Start~~~~~~~~~")
$startTime = Get-Date
Write-Host ("Start time: " + $startTime)
Write-Host ("Files to be copied from: " + $env:JenkinsMasterMachine)
Write-Host ("Will copy files to: " + $env:FilesCopyTo)
Write-Host ("~~~~~~~~~~~~~~~~~~~~~~~")

$pathFrom = $env:JenkinsMasterMachine
$pathTo = $env:FilesCopyTo

#jobs folder will be handled specifically; 
#arechiveLogs is created by Allen, no need copy
#archiveLogs contains too many small files, no need copy
$foldersNotWantToCopyDirectly = "jobs", "config-history", "archiveLogs"; 

# Following 2 files are using by Jenkins, no need copy
$filesNotWantToCopy = "jenkins.err.log", "jenkins.out.log";


# Create FilesCopyTo folder
if (! (Test-Path $pathTo))
{
   Write-Host ("Going to create folder: " + $pathTo)
   md $pathTo
}
else
{
   Write-Host ("Already exist folder: " + $pathTo)
}


Get-ChildItem $pathFrom | Foreach-Object -Process{
   if ($_ -is [System.IO.FileInfo]-and ($filesNotWantToCopy -notcontains $_.name) -and ($_.name -notmatch ".*.tmp") ) 
   {
   	Write-Host ("Is copying file: " + $_.name);
	Copy-Item $pathFrom\$_ $pathTo -Force
   }
   elseif ($_ -is [System.IO.FileInfo])
   {
   	Write-Host ("+++++++++ Won't copy file: " + $_.name);
   }
   if ($_ -is [System.IO.DirectoryInfo] -and ($foldersNotWantToCopyDirectly -notcontains $_.name))
   {
   	Write-Host ("Is copying folder: " + $_.name);
	Copy-Item -Recurse $pathFrom\$_ $pathTo -Force 
	#copy (also override if exist) the folders (including contents) to target place
	# but "jobs" folder won't be copied. Will handle specifically in next segment
   }
}


# Copy Jobs folder - for the jobs in it, will NOT copy "<jobname>\builds" folder
# because there are a huge number of small files in builds folder

$jobs = Get-ChildItem $pathFrom\jobs

Write-Host ("======================")

$jobs #Show all the files/folders in "jobs" folder

$count = $jobs.Count           

For($i=0; $i -lt $count; $i++) {          
	Write-Host ($pathFrom + "\jobs\" + $jobs[$i]);
	Get-ChildItem ($pathFrom + "\jobs\" + $jobs[$i]) |ForEach-Object -Process{
			Write-Host ("Is copying job file: " + $jobs[$i] + "\" + $_);
			Copy-Item ($pathFrom + "\jobs\" + $jobs[$i] + "\" + $_) ($pathTo + "\jobs\" + $jobs[$i]) -Force;
	}
        Write-Host ("~~~~~~~~~~~~~~~~~~~~~~");
}

$endTime = Get-Date
Write-Host ("End time: " + $endTime)
Write-Host ("Total execution time in 'Minutes': " + ($endTime-$startTime).TotalMinutes )
Write-Host ("============ End ============")

  fdfdfd

 

posted @ 2016-04-03 08:32  allenbackpacker  阅读(204)  评论(0)    收藏  举报