Link to home
Start Free TrialLog in
Avatar of Gonzalo Becerra
Gonzalo BecerraFlag for Argentina

asked on

Script Sharepoint Backup

Hi guys,

I need help to modify this Powershell script:

How can i modify all filenames change date instead GUID.
How to pass as parameter
     - sitecollectionurl
     - backupdestination
and don't read this parameters from the XML.

Script:
 
#Get XML configuration file parameter
param (    
    [string]$Configurationfile = $(throw "need parameter Configurationfile (e.g. ""c:\SPBackup\SPBackup.xml"")")    
)   

function Logging { 
 $logmsg = $args[0] 
 Write-Host $logmsg
 $jobreport+[Environment]::NewLine+[System.DateTime]::Now
 $logmsg
}

function sendemail
{
#  ---
#  --- Report to e-mail if email and smtpserver is defined ---
#  ---
 If ($fromemail)
 {
  If ($toemail)
  {
   If ($smtpserver)
   {
    $jobreport = logging("Ending with job status """+$jobstatus+""" for site id "+$id)
    $jobreport = logging("Sending job report on email")
    $subject = $jobstatus +": SPBackup has completed on "+$env:computername+" with "+[System.DateTime]::Now
    $msg = new-object System.Net.Mail.MailMessage $fromemail, $toemail, $subject, $jobreport
    $client = new-object System.Net.Mail.SmtpClient $smtpserver
    $client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
    $client.Send($msg) 
   }
   else
   {
    $jobreport = logging("Skipping Report to e-mail because of missing smtpserver")
   }
  }
  else
  {
   $jobreport = logging("Skipping Report to e-mail because of missing toemail address")
  }
 }
 else
 {
  $jobreport = logging("Skipping Report to e-mail because of missing fromemail address")
 }
}

function out-zip { 
 $path = $args[0] 
 $files = $input 

 if (-not $path.EndsWith('.zip')) {$path += '.zip'} 

 if (-not (test-path $path)) 
 { 
  set-content $path ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 
 } 

 $zipfile = (new-object -com shell.application).NameSpace($path) 
 $files | foreach {$zipfile.CopyHere($_.fullname) } 
} 

If (Test-Path $Configurationfile) {
   $cfg = [xml] (get-content $Configurationfile)
   $jobreport = logging("Started backup with configuration file "+$Configurationfile)
} 
Else 
{   
   $jobstatus="Error"
   $jobreport = logging( "Error: Configuration XML file not found!")
   sendemail
   exit
}
$QueryOS = Gwmi Win32_OperatingSystem -Comp localhost 
$QueryOS = $QueryOS.Caption 

If ($QueryOS.contains("2008") -or $QueryOS.contains("Vista"))
{
$jobreport = logging("Windows Server 2008 or Vista detected")
}

If ($QueryOS.contains("2003"))
{
$jobreport = logging("Windows Server 2003 detected")
}

#Go through each site-configuration in the file
$nodelist = $cfg.selectnodes("/confSPBackup/site")
foreach ($item in $nodelist) {
   #Read this site parameters
   $jobstatus="Success"
   $id = $item.getAttribute("id")
   $catastrophicbackup = $item.catastrophicbackup
   $catastrophicmethod = $item.catastrophicmethod
   $sitecollectionbackup = $item.sitecollectionbackup
   $sitecollectionurl = $item.sitecollectionurl
   $hivebackup = $item.hivebackup
   $hive = $item.hive 
   $iisbackup = $item.iisbackup
   $iisencryptopassword = $item.iisencryptopassword
   $smtpserver = $item.smtpserver
   $fromemail = $item.fromemail
   $toemail = $item.toemail
   $backupdestination = $item.backupdestination
   $backupdestinationmaxkeepdays = $item.backupdestinationmaxkeepdays
   $backupfilename = $sitecollectionurl.replace("http://","")
   $backupfilename = $backupfilename.replace("/","_")
   $guid = "-" + [Guid]::NewGuid().ToString() 
      
   #Print the configuration parameter-details
   $jobreport = logging("Starting session"+$guid)
   $item 

   #  ---
   #  --- Delete old files from backupdestination if backupdestinationmaxkeepdays<>0 ---
   #  ---
   If ([string]::Compare($backupdestinationmaxkeepdays, "0", $True)) 
   {
      #Perform deletion if backup destination path is valid
      if(test-path $backupdestination)  
      { 
	& dir $backupdestination |? {$_.CreationTime -lt (get-date).AddDays(-$backupdestinationmaxkeepdays) -and $_.name.EndsWith('.zip')} | del -force
	& dir $backupdestination |? {$_.CreationTime -lt (get-date).AddDays(-$backupdestinationmaxkeepdays) -and $_.name.EndsWith('.backup')} | del -force
        [DateTime]::Now.ToString() +  ": Files on backup destination "+$backupdestination+" older than "+$backupdestinationmaxkeepdays+" days deleted!" 
      }  
      else 
      {  
         $jobstatus="Error"
         $jobreport = logging("Error: The backupdestination Path doesn't exists for site id "+$id)
      }
   }
   else
   {
   $jobreport = logging("Skipping deletion of old files on backupdestination")
   }

   #  ---
   #  --- Do a hive backup if hivebackup=1 ---
   #  ---
   If ([string]::Compare($hivebackup, "0", $True)) 
   {
     $jobreport = logging("Starting backup of hive "+$hive+" to "+$backupdestination+"\"+$backupfilename+"-12hive"+$guid+".zip")
     if(test-path $backupdestination)  
      { 
	if(test-path $hive)  
        { 
	gi $hive | out-zip $backupdestination"\"$backupfilename"-12hive"$guid".zip" $_
	[DateTime]::Now.ToString() +  ": Hive backup Done! File name is $backupdestination\$backupfilename-12hive$guid.zip" >> "$backupdestination\log.txt" 
      	}  
	else 
      	{  
           $jobstatus="Error"
           $jobreport = logging("Error: The 12hive Path doesn't exists for site id "+$id)
      	}
      }
      else 
      {  
        $jobstatus="Error"
   	$jobreport = logging("Error: The backupdestination Path doesn't exists for site id "+$id)
      }
   }
   else
   {
   $jobreport = logging("Skipping backup of hive "+$hive)
   }
   Start-sleep 30

   #  ---
   #  --- Do a IIS Metadata backup if iisbackup=1 ---
   #  ---
   If ([string]::Compare($iisbackup, "0", $True)) 
   {
     $jobreport = logging("Starting backup of IIS Metadata to "+$backupdestination+"\"+$backupfilename+"-IISMetadata"+$guid+".zip")
     if(test-path $backupdestination)  
      { 
       If ($QueryOS.contains("2003"))
       {
	if(test-path $env:windir\system32\inetsrv\metaback)  
        {
	#Check if iisuser and iispassword are entered if not run the iisback.vbs with local machine encryption
	#With local machine encryption the IIS Metadata can only be restored on this particullar IIS instance/Server
	If ($iisencryptopassword)
 	{
	    $jobreport = logging("The IIS Metadata is done using encryption password specified")
	    & cscript.exe $env:windir\system32\iisback.vbs /backup /e $iisencryptopassword /b $env:computername /overwrite
	}
	else
	{
	 $jobreport = logging("The IIS Metadata is done using machine credentials (restore on same IIS instance/server only)")
	 & cscript.exe $env:windir\system32\iisback.vbs /backup /b $env:computername /overwrite
	}
	ls $env:windir\system32\inetsrv\metaback\$env:computername.* | out-zip $backupdestination"\"$backupfilename"-IISMetadata"$guid".zip" $_
	[DateTime]::Now.ToString() +  ": IIS Metadata backup Done! File name is $backupdestination\$backupfilename-IISMetadata$guid.zip" >> "$backupdestination\log.txt" 
      	}  
	else 
      	{  
           $jobstatus="Error"
   	   $jobreport = logging("Error: The IIS Metadata Path doesn't exists for site id "+$id)
      	}
       }
       If ($QueryOS.contains("2008"))
       {
        & $env:windir\system32\inetsrv\appcmd.exe add backup
        gi $env:windir\system32\inetsrv\backup | out-zip $backupdestination"\"$backupfilename"-IISMetadata"$guid".zip" $_
	[DateTime]::Now.ToString() +  ": IIS Metadata backup Done! File name is $backupdestination\$backupfilename-IISMetadata$guid.zip" >> "$backupdestination\log.txt" 
      	
       }
      }
      else 
      {  
        $jobstatus="Error"
   	$jobreport = logging("Error: The backupdestination Path doesn't exists for site id "+$id)
      }
   }
   else
   {
   $jobreport = logging("Skipping backup of IIS Metadata ")
   }
   Start-sleep 10

   #  ---
   #  --- Do a site collection crawl and backup if sitecollectionbackup=1 ---
   #  ---
   If ([string]::Compare($sitecollectionbackup, "0", $True)) 
   {
      $jobreport = logging("Starting backup of individual site "+$sitecollectionurl+" to "+$backupdestination+"\"+$backupfilename+$guid+".backup")
        
      #Perform backup if backup destination path is valid
      if(test-path $backupdestination)  
      { 
	& $hive\BIN\stsadm.exe -o backup -url $sitecollectionurl -filename $backupdestination"\"$backupfilename$guid.backup -overwrite > $null
        [DateTime]::Now.ToString() +  ": Site backup Done! File name is $backupdestination\$backupfilename$guid.backup" >> "$backupdestination\log.txt" 
      }  
      else 
      {  
         $jobstatus="Error"
         $jobreport = logging("Error: The backupdestination Path doesn't exists for site id "+$id)
      }
   }
   else
   {
   $jobreport = logging("Skipping backup of individual site "+$sitecollectionurl)
   }

   #  ---
   #  --- Do a farm backup if catastrophicbackup=1 ---
   #  ---
   If ([string]::Compare($catastrophicbackup, "0", $True)) 
   {
      $jobreport = logging("Starting catastrophic backup of farm to "+$backupdestination+"\")
        
      #Perform backup if backup destination path is valid
      if(test-path $backupdestination)  
      { 
	& $hive\BIN\stsadm.exe -o backup -directory $backupdestination"\" -backupmethod $catastrophicmethod -overwrite > $null
        [DateTime]::Now.ToString() +  ": Farm backup Done! Destination is $backupdestination\" >> "$backupdestination\log.txt" 
      }  
      else 
      {  
         $jobstatus="Error"
         $jobreport = logging("Error: The backupdestination Path doesn't exists for site id "+$id)
      }
   }
   else
   {
   $jobreport = logging("Skipping catastrophic backup of farm with xml site id "+$id)
   }
sendemail
$jobreport=""
}
Write-host([Environment]::NewLine+[Environment]::NewLine+"SPBackup has ended, waiting 40 seconds for jobs to complete...")
Start-Sleep 40

Open in new window


xml
 
<?xml version="1.0" ?>
<confSPBackup>
   <site id="1">
	<catastrophicbackup>1</catastrophicbackup>
	<catastrophicmethod>full</catastrophicmethod>
	<sitecollectionbackup>1</sitecollectionbackup>
	<sitecollectionurl>http://Sitecollection</sitecollectionurl>
	<hivebackup>1</hivebackup>
	<hive>C:\Program Files\Common Files\Microsoft Shared\web server extensions\12</hive>
	<iisbackup>1</iisbackup>
	<iisencryptopassword>123456</iisencryptopassword>	
	<smtpserver></smtpserver>
	<fromemail>=</fromemail>
	<toemail></toemail>
	<backupdestination>E:\Temp\Backups</backupdestination>
	<backupdestinationmaxkeepdays>0</backupdestinationmaxkeepdays>
   </site>
</confSPBackup>

Open in new window

Avatar of GeorgeGergues
GeorgeGergues

can you post a sample of that xml file .

the configuration parameters are in that file.
Also,
I think the number of parameters are a bit large , why do want to run from the command line rather than using the xml parameter/config file ?
Avatar of Gonzalo Becerra

ASKER

Because i think automatize the process with a Vbscript call to this script and pass 3 parameters XMLFile SiteCollectionToBackup and BackupDestination.
it's possible don;t read these parameters from xml file and receieve by parameter? what i need modify?
ASKER CERTIFIED SOLUTION
Avatar of Gonzalo Becerra
Gonzalo Becerra
Flag of Argentina image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I need help to modify all filenames change date instead GUID.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I am sorry about the delay , I had no access to work question.

That change will do the time date trick.

Are you still interested to get the variables from the command line or still use xml config file ?
George no problem, thank you. I'm using variable I has been changed the script to take these variables as parameters.
Also I changed the code to change the name of the file with date.

Thanks in advance
I accept my comment because i found the solution