Tags

, , ,

Hi Friends,

One more blog with a helper script.

This script does multiple things.

It copies selected folders and files from a given path, zips the folders, and copies it in the backup folder under the current location named with the current date and time.

Details

  • It creates a new folder in current folder with current date and time in yyyy-MM-dd-hh-mm-ss format. 2 advantages of creating the folder like this. No more random names for backup and second one is, the folders are sortable correctly always.
  • Then it reads the source folder defined in source path variable.
  • From the source folder, if the name matches the names we defined in the array variable “folders”, it will zip the individual folders and copy that to the new folder. If the item is file then it will just copy not zip.
<#
Script is created by Maulik Darji
https://darjimaulik.wordpress.com
#>
#Change the site name frome below location or set any source path
$sourcePath = "C:\inetpub\wwwroot\sc102.sc.com"
#destination path is set as current folder
$destinationPath = get-location
#set the folders and file names in the array below. 
$folders = 'app_config','bin','views','web.config'
#Folder will be created with seconds as well. 
$folderName = (Get-Date).tostring("yyyy-MM-dd-hh-mm-ss")
Add-Type -assembly "system.io.compression.filesystem"
New-Item -itemType Directory -Path $destinationPath -Name $folderName
$newDestinationPath = "$($destinationPath)\$($folderName)"
write-host $newDestinationPath
$source = Get-ChildItem -Path $sourcePath -Filter "*" 
Foreach ($s in $source)
{
	if($folders -match $s.name)
    {
		if ($s.gettype() -eq [System.IO.DirectoryInfo])
		{
			$destination = Join-path -path $newDestinationPath -ChildPath "$($s.name).zip"
			If(Test-path $destination) 
			{
				Remove-item $destination
			}
			[io.compression.zipfile]::CreateFromDirectory($s.fullname, $destination)
		}
		else
		{
			$source = Join-path -path $sourcePath -ChildPath "$($s.name)"  
			$destination = Join-path -path $newDestinationPath -ChildPath "$($s.name)"
			Copy-Item -Path $source  -Destination $newDestinationPath 
		}	
	}
}