→ 🚀What's New? Explore Lansweeper's Fall 2024 Updates! Fall Launch Blog !

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
WebbYates
Engaged Sweeper
I wrote a backup script to backup Lansweeper as per their guidelines (https://www.lansweeper.com/knowledgebase/backing-up-your-installation/). I've seen a few scripts on here, so i've taken them all, along with the guidelines to make this.

Here it is. Customisations and comments welcome.
Also available on Github - https://github.com/mortensummer/PoSH-Chocs/


<#
.SYNOPSIS
Backups up Lansweeper data as per their guidance notes

.DESCRIPTION
This PowerShell script will backup the Lansweeper data and database according to their suggested guidelines.

.PARAMETER SQL
Is the database SQL Express or full SQL? (e.g. NOT Compact SQL)

.PARAMETER Destination
Where to copy the backup to

.PARAMETER BackupsToKeep
How many previous days worth of backups to keep in the destination folder

.EXAMPLE
.\Backup-Lansweeper.ps1 -SQL -Destination C:\backups -BackupsToKeep 14
Backups up Lansweeper to the C:\Backups folder, and removes backups older than 14 days.

.NOTES
Version 1.0
Written by: Tom Yates
#>

[CmdletBinding(DefaultParameterSetName='Main')]
Param(
[Parameter(ParameterSetName='Main', Mandatory=$true)]
[Switch]$SQL,

[Parameter(ParameterSetName='Main', Mandatory=$true)]
[String]$Destination,

[Parameter(ParameterSetName='Main', Mandatory=$false)]
[int]$BackupsToKeep
)


$WebsiteFolders = @(
'website\actions',
'website\assetpictures',
'website\docs',
'website\images',
'website\userpictures',
'website\widgetscustom',
'website\app_data',
'website\customdata',
'website\lang',
'website\widgetscustom'
)

$rootFolders =@(
'actions',
'key',
'packageshare',
'iisexpress',
'sqldata'
)

$helpdeskfolders =@(
'website\helpdesk\files',
'website\helpdesk\icons'
)

$knowledgebaseFolders= @(
'website\knowledgebase\kbfiles'
)
$ServiceFolders =@(
'service\export'
)

### System Variables ###
$LSRoot = "C:\Program Files (x86)\Lansweeper" # Lansweeper Installation Folder
$LSDBServer = "localhost" # Lansweeper Database Server (If not using SQL Compact)
$LSDBName = "lansweeperdb" # Lansweeper Database Name (If not using SQL Compact)

#Which services need to start/stop as part of this backup process?
$DependantServices = "W3SVC","IISExpressSVC","LansweeperService"

$DatetoDelete = (Get-Date).AddDays(-$BackupsToKeep)
$Date = Get-Date -Format 'ddMMyy-HHmmss'

$FilePrefix = "Lansweeper_Backup_"
$Name = "$FilePrefix$Date"

#Set up a working folder for creating the ZIP file
$WorkingFolder = Join-Path -path $env:temp -childpath $([System.IO.Path]::GetRandomFileName())
New-item -Path $WorkingFolder -ItemType Directory

$TempPath = Join-Path -Path $WorkingFolder -ChildPath $Name
$ZipBackup = Join-Path $WorkingFolder "$Name.zip"

#SQL Query to backup the database (if not using SQL Compact)
$LSDBBackup = "$TempPath\$LSDBName$Date.bak" # Name of Database Backup
$SQLQuery = "BACKUP DATABASE $LSDBName TO DISK = N'$LSDBBackup' WITH NOFORMAT, INIT, NAME = N'Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10"

function Copy-Folders([string]$Dest, [psobject]$SourceFolders){
foreach($folder in $SourceFolders){
Copy-Item "$LSRoot\$Folder\" $Dest -Recurse -Force
}
}
function Switch-Services([string]$action, $services){
Foreach ($service in $services){
Switch ($action){
"stop"{
If (Get-Service $service -ErrorAction SilentlyContinue) {
If ((Get-Service $service).Status -eq 'Running') {Stop-Service $service}
}
else{Write-Verbose "$Service :Not Found" }
}
"start" {
If (Get-Service $service -ErrorAction SilentlyContinue) {
If ((Get-Service $service).Status -eq 'Stopped') {
If((Get-Service $service).StartType -eq 'Disabled'){
Write-Verbose "$Service :Set to Disabled"
}
Else{
Write-Verbose "Starting Service $service"
Start-Service $service
}
}
}
}
}
}
}
#Stop Services
Switch-Services "stop" $DependantServices

#Website
$WebsiteFolderBackup = New-Item -Path $TempPath -ItemType Directory -Name "website"
Copy-Folders $WebsiteFolderBackup $WebsiteFolders

#helpdesk
$HelpdeskFolderBackup = New-Item -Path $WebsiteFolderBackup -ItemType Directory -Name "helpdesk"
Copy-Folders $HelpdeskFolderBackup $helpdeskfolders

#knowledgebase
$KBFolderBackup = New-Item -Path $WebsiteFolderBackup -ItemType Directory -Name "knowledgebase"
Copy-Folders $KBFolderBackup $knowledgebaseFolders

#service
$ServiceFolderBackup = New-Item -Path $TempPath -ItemType Directory -Name "service"
Copy-Folders $ServiceFolderBackup $ServiceFolders

#Root
Copy-Folders $TempPath $rootFolders

#Backup Database if SQL parameter is set.
If ($SQL){SQLCMD.EXE -S $LSDBServer -E -Q $SQLQuery}

#Start Services
Switch-Services "start" $DependantServices

#Zip it up
$Finish = Get-ChildItem $TempPath
Compress-Archive -Path $Finish.FullName -DestinationPath $ZipBackup

#Calculate Hash
$OriginalHash = Get-FileHash -Path $ZipBackup -Algorithm MD5

#Copy file to destination
try{
$FileBackup = Copy-Item -Path $ZipBackup -Destination $Destination -PassThru -ErrorAction Stop
}catch{
Write-Warning "Could not copy $FileBackup to $destination."
Exit
}

#Calculate Hash afer copying
$CopiedHash = Get-FileHash -Path $FileBackup.FullName -Algorithm MD5

#Compare hashes
If ($OriginalHash.hash -ne $CopiedHash.hash){
Write-Warning "Hash Mismatch when copying. Not cleaning up."
Write-Warning "Please check folder $WorkingFolder"
}else{
Write-Verbose "Removing $WorkingFolder as the file hash matched"
remove-Item $WorkingFolder -Force -Recurse

If($BackupsToKeep){
Write-Verbose "Removing files older than $Backupstokeep days"
Get-ChildItem $Destination -Filter "$FilePrefix*.zip" | Where-Object {$_.LastWriteTime -lt $DatetoDelete} | Remove-Item
}
}

4 REPLIES 4
Brown_Dog_NG
Champion Sweeper

Dead thread, sorry to reopen but wanted to contribute.

I'm not very familiar with SQL so excuse my ignorance. I'm not sure if there is a difference in SQL Local DB and SQL 16. The solution I've found for SQL 16 is using Microsoft SQL Server Management Studio via this link (Opt 2). I've extracted the steps from the site in the event the link goes bad. I hope it helps.

1. Log into your SQL Server via Microsoft SQL Server Management Studio
2. Right-click SQL Server Agent, select Start to enable this function.
3. Open up SQL Server Agent tab, right-click Job > New Job…
4. On General page, fill the name in the blank.
5. Turn to Step page, click New… and fill in Step name in the prompt window. Select T-SQL in Type, then input following statements in Command:>

DECLARE @strPath NVARCHAR(200)
set @strPath = convert(NVARCHAR(19),getdate(),120)
set @strPath = REPLACE(@strPath, ':' , '.')
set @strPath = 'filepath' + @strPath + '.bak'
BACKUP DATABASE [databasename] TO DISK = @strPath WITH NOINIT , NOUNLOAD , NOSKIP , STATS = 10, NOFORMAT

Note: as for the ‘filepath’ part you need to fill in the path created before to store these backups. For example: D:\Backup.
Then click OK.>

6. Turn to Schedules page, click New… and fill in Schedule name, select the Frequency and Duration in the prompt window. Click OK to save these settings.
7. Find the newly created job in SQL Server Agent > Jobs, right-click it and select Start Job at Step to start.

 

-Don't forget to hand out Kudos and mark Solutions to replies you receive!-
LS Tech Support Email: Support@lansweeper.com
LS Tech Support KB: https://www.lansweeper.com/contact-support/
looktall
Engaged Sweeper III
I've tried it out and it works well.

I had to run it as administrator in order to get the SQL component to work.
looktall wrote:
I've tried it out and it works well.

I had to run it as administrator in order to get the SQL component to work.


Thanks for the reply.

I have never been able to get an automated backup to work. I think it's because I have it set on a LocalDB database and not a true full SQL database.
JStowers
Engaged Sweeper
Has anyone tried this script or wrote a similar script to backup Lansweeper?

I've tried using this script and tweaking it a bit as well. It will backup the folders, but I can't seem to ever get it to actually backup the database. This is using SQL LocalDB.

Thanks!