Mongodb Backup using Powershell Script
Take mongodb backup using powershell script....
- Create mongodb database backup
- Compress backup file in zip file
- Upload backup zip file on Azure blob storage
cls
#Set Variables
$environment = "EnvironmentName"
$database = "DatabaseNaMe"
$server = "localhost/IP:portnumber"
$timestamp = get-date -format yyyy-MM-dd-hh-mm-ss
$backupPath = 'D:\Backup\'
$directoryName = "$database-$timestamp"
$directoryPath = Join-Path $backupPath $directoryName
$fileName = "$directoryName.$archiveType"
$filePath = Join-Path $backupPath $fileName
$Watch = New-Object System.Diagnostics.StopWatch
$Watch.Start()
#Create mongodb backup
Write-Host "Backing up '$fileName' to local directory: $backupPath."
&'C:\Program Files\MongoDB\Server\3.0\bin\mongodump.exe' -h $server -d $database -o "$directoryPath"
#Create zip file
$source = $directoryPath
$directoryName = $environment + "-$directoryName"
$destination = Join-Path $backupPath "$directoryName.zip"
If(Test-path $destination) {Remove-item $destination}
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($Source, $destination)
#Upload Backup Script on Azure blob storage
$localFileDirectory = "D:\backup\"
$StorageAccountName = "storageAccountname"
$StorageAccountKey = "AccountKey"
$ContainerName = "ContainerName"
$ctx = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
#Create container
#New-AzureStorageContainer -Name $ContainerName -Context $ctx -Permission Blob
#Get files list from folder
$files = Get-ChildItem $localFileDirectory *.zip
#process each file
foreach($fileName in $files)
{
$localFile = $localFileDirectory + $fileName
$azblob = Get-AzureStorageBlob -Blob $fileName -Container $ContainerName -Context $ctx -ErrorAction SilentlyContinue
If ($azblob -ne $null) {
# Blob already exists, check the lastwrite metadata
Write-Host $fileName " file exists"
} Else {
#Upload file in storage
Set-AzureStorageBlobContent -File $localFile -Blob $fileName -Container $ContainerName -Context $ctx -Force -ErrorAction SilentlyContinue
#Remove file after upload file
Remove-Item $localFile
}
}
Write-Host "Backup file uploaded on storage..."
#Get files list from folder
$folders = Get-ChildItem $localFileDirectory -Directory
foreach($folderName in $folders)
{
$folder = $localFileDirectory + "\" + $folderName
Remove-Item -recurse -force $folder #-erroraction silentlycontinue
}
$Watch.Stop();
Hope this will help you and save your time.
Enjoy !!!
:)
No comments:
Post a Comment