Giter VIP home page Giter VIP logo

powershell-backup-script's Introduction

This Script is not longer maintained. Feel free to adapt it as you need it.

Name: BackupScript.ps1

Creator: Michael Seidl aka Techguy
CreationDate: 05.08.2021 
LastModified: 05.11.2021 
Version: 2.1
Doc: http://www.techguy.at/tag/backupscript/
GitHub: https://github.com/Seidlm/PowerShell-Backup-Script
PSVersion tested: 5

PowerShell Self Service Web Portal at https://www.au2mator.com/PowerShell

Description:

Copies the Bakupdirs to the Destination You can configure more than one Backupdirs, every Dir wil be copied to the Destination. Only Change Variables in Variables Section Change LoggingLevel to 3 an get more output in Powershell Windows

Version 2.1 (05.11.2021)

FIX: Root Files are now inlcuded in Backup

Version 2.0 (05.08.2021)

Published v2 Verion

Version 1.5 (31.03.2020)

FIX: Github: Symbolic Links are now supported
FIX: Github: Sibling Folders
FIX: Github: Backup Duration
NEW: Rewrite Loggign Function
DIF: Some Code write ups

Version 1.4

NEW: 7ZIP Support
FIX: Ordering at old Backup deletion
FIX: Exclude Dir is now working
NEW: Staging folder for ZIP

Version 1.3

NEW: Send Mail Function
NEW: Backup Destination will be zipped
NEW: Exclude Dir
FIX: Logging Level
FIX: Delete old Folder by CreationTime

Version 1.2

FIX: Delete last Backup dirs, changed to support older PS Version
FIX: Fixed the Count in the Statusbar
FIX: Fixed Location Count in Statusbar

Version 1.1

CHANGE: Enhanced the Logging to a Textfile and write output, copy Log file to Backupdir
FIX: Renamed some Variables an have done some cosmetic changes
CHANGE: Define the Log Name in Variables

Version 1.0 - RTM

Notes

www.techguy.at
www.facebook.com/TechguyAT
www.twitter.com/TechguyAT
[email protected]

powershell-backup-script's People

Contributors

osemc3 avatar seidlm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

powershell-backup-script's Issues

Junction Link giving errors

This is a low priority issue but when I run the script I get the following errors.
Is their away to tell the script to ignore Junction Links?
Adding them to the "ExcludeDirs" does not do anything.
Skipping "C:\Users\Grayfox\AppData\Local\Application Data" Error: PermissionDenied: (C:\Users\Grayfo...pplication Data:String) [Get-ChildItem], UnauthorizedAccessException Skipping "C:\Users\Grayfox\AppData\Local\History" Error: PermissionDenied: (C:\Users\Grayfox\AppData\Local\History:String) [Get-ChildItem], UnauthorizedAccessException Skipping "C:\Users\Grayfox\AppData\Local\Microsoft\Windows\INetCache\Content.IE5" Error: PermissionDenied: (C:\Users\Grayfo...che\Content.IE5:String) [Get-ChildItem], UnauthorizedAccessException Skipping "C:\Users\Grayfox\AppData\Local\Microsoft\Windows\Temporary Internet Files" Error: PermissionDenied: (C:\Users\Grayfo... Internet Files:String) [Get-ChildItem], UnauthorizedAccessException Skipping "C:\Users\Grayfox\AppData\Local\Temporary Internet Files" Error: PermissionDenied: (C:\Users\Grayfo... Internet Files:String) [Get-ChildItem], UnauthorizedAccessException Skipping "C:\Users\Grayfox\Application Data" Error: PermissionDenied: (C:\Users\Grayfox\Application Data:String) [Get-ChildItem], UnauthorizedAccessException Skipping "C:\Users\Grayfox\Cookies" Error: PermissionDenied: (C:\Users\Grayfox\Cookies:String) [Get-ChildItem], UnauthorizedAccessException

Thank you.

Notification Mail Attachement

Hello TechGuy!

Thanks for the effort and more thanks for sharing it!
It's pretty cool!
The Script work's fine so far! Just try to understand how it works and expand the functionality a bit!
Added the Lines:
Snip...
##SEND NOTIFICATION MAIL
Write-au2matorLog -Type Info -Text "Send Info Mail about new BackUp to Chef Andreas"

Send-MailMessage -From AndreasEMAIL.com -Subject "Ein neues Inca FehlerLog Backup wurde erstellt" -To AndreasEMAIL.com -Body "INCA FehlerLogdaten Backup wurde erstellt!" -BodyAsHtml -SmtpServer SMTPSERVERADDRESS.com
...endSnip

Works well and send me the notification via email. If it runs on my system there is no need for auth.
If i try to add the "Attachement" -> "LogFile" which is predefined at the beginning of script it's not gonna work!
I'am pretty new to the "power of shell" so forgive me if this is a dumb question to you!
Greetings Andreas

Error running in PowerShellISE

I ran into an issue that I was able to fix.
I use PowerShellISE so I can interactively work on scripts and run them easily.

At the end of the script, I get:

Exception calling "ReadKey“ with "1“ argument(s): "The method or operation is not implemented.“
At C:\Users\Downloads\BackupScript.ps1:356 char:1

  • $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown“)
  • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
  • FullyQualifiedErrorId : NotImplementedException

After some searching, I found that ReadKey does not work in PowerShellISE.
A solution I found that works in PowerShell and PowerShellISE was at
https://stackoverflow.com/questions/20886243/press-any-key-to-continue
I added the following function:

Function pause ($message) { # Check if running Powershell ISE if ($psISE) { Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.MessageBox]::Show("$message") } else { Write-Host "$message" -ForegroundColor Yellow $x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown") } }

and replaced the following line from the original script, not in the function:
$x = $host.ui.RawUI.ReadKey(„NoEcho,IncludeKeyDown“)

with
pause "Press any key to close …“

In PowerShellISE it brings up a Windows Message Box which could be pushed to the background and missed by the user.

Works like a charm for me.

PermissionDenied error occurs in some conditions

Remove-Item : Cannot remove item C:\Users\UserName\Downloads\Backup-2020-02-26-1212\Documents\SomeFolder\a_file.pdf: You do not have sufficient access rights to perform this operation.
At line:1 char:1
+ Remove-Item -Path .\Backup-2020-02-26-1212 -Recurse
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (a_file.pdf:FileInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand
Remove-Item : Directory C:\Users\UserName\Downloads\Backup-2020-02-26-1212\Documents\SomeFolder cannot be removed because it is not empty.
At line:1 char:1

You can correct this error by adding "-Force" key to "Remove-Item" command at line 305, so it would look the following way:
Get-ChildItem -Path $Staging -Recurse -Force | remove-item -Confirm:$false -Recurse -Force

SendMail issue

Using your latest version on Server 2012R2 with PS version 4... Got this message after it finished copying.

Send-MailMessage : Cannot validate argument on parameter 'Attachments'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At C:\Users[redacted]\Desktop\BackupScript.ps1:255 char:131

  • ... TP -attachment $Log
  •                ~~~~
    
    • CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingValidationException
    • FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SendMailMessage

Any suggestions?

Error running backupscript.ps1

$SumItems += $colItems.Count

There appears to be an error in the script posted on GitHub at line 203. The error is "you cannot call a method on a null-valued expression"

Create Backupdir J:\Backups\Backup-2020-05-18-45752\

Start the Script
Check if there are more than 15 Directories in the Backupdir
Check if there are more than 15 Zip in the Backupdir
Check if BackupDir and Destination exists
Started the Backup
Count all files and create the Top Level Directories
You cannot call a method on a null-valued expression.
At C:\Users*****\OneDrive\Documents\WindowsPowerShell\MyScripts\01-BackUpScript1.5.ps1:219 char:3

  •     $SumMB += $colItems.Sum.ToString()
    
  •     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (:) [], RuntimeException
    • FullyQualifiedErrorId : InvokeMethodOnNull

There are 0 Files with 0.00 MB of Files to copy

Copied 1 files with 0.00 MB of Files
0 Files could not be copied
Backup duration 0 hours 0 minutes 5 seconds


Win10 Pro script fail when run via task scheduler

Hi

I'm running the last version of the script via the windows Task Scheduler on a Windows 10 pro up-to-date.
Manually (Right clic on the script file, "Run with PowerShell"), the script runs great !

When it runs via the task scheduler (At 1am everyday), script fails with this error (in the log)
"14.07.2020-01:00:07: <9920> One of the Directories are not available, Script has stopped"
20200714_Log.log

I checked in the script why, and saw the "Check-Dir" function should log the cause (even source or destination is unreachable). But none of the 2 messages are in the log. (Attached, one of the log file.

Other information that may be helpfull

  • Source are local files (On C: and D: drives)
  • Destination is a remote repository (On a Freenas) mapped in windows (Z:)
  • Computer is on, session open and Z: is working well.

And here is my backup configuration

#Variables, only Change here
$Destination = "Z:\BCKP\Asterix" #Copy the Files to this Location
$Staging = "D:\BCKP\staging"
$ClearStaging = $true # When $true, Staging Dir will be cleared
$Versions = "15" #How many of the last Backups you want to keep
$BackupDirs = "C:\Users\Dergonic", "D:\Stream" #What Folders you want to backup

$ExcludeDirs = #This list of Directories will not be copied
($env:SystemDrive + "\Users\.*\AppData\Local"),
($env:SystemDrive + "\Users\.*\AppData\LocalLow")

$LogfileName = "Log" #Log Name
$LoggingLevel = "3" #LoggingLevel only for Output in Powershell Window, 1=smart, 3=Heavy
$Zip = $true #Zip the Backup Destination
$Use7ZIP = $true #Make sure it is installed
$RemoveBackupDestination = $true #Remove copied files after Zip, only if $Zip is true
$UseStaging = $true #only if you use ZIP, than we copy file to Staging, zip it and copy the ZIP to destination, like Staging, and to save NetworkBandwith



#Send Mail Settings
$SendEmail = $false                    # = $true if you want to enable send report to e-mail (SMTP send)
$EmailTo = '[email protected]'              #[email protected] (for multiple users use "User01 &lt;[email protected]&gt;" ,"User02 &lt;[email protected]&gt;" )
$EmailFrom = '[email protected]'   #matthew@domain 
$EmailSMTP = 'smtp.domain.com' #smtp server adress, DNS hostname.

Exclude files does not work properly

I am using large parts of the Backup-Script for PowerShell
All works well besides I am having trouble to exclude “C:\Program Files (x86)”. I put it into $Exclude and it is there even correct in REGEX format but at the end it does not work ☹.
Any help or hint would be highly appreciated.
Cheers
Thomas

Files in the root folder are not being copied

Hello,
thank you for your script.

Aside from a small issue with the log attachment (which I solved by declaring the $Log variable, it must have been lost between versions), I have noticed that files in the root folder are not being backed up, while the contents of subfolders all copy correctly.

I.E.:

C:\Folder\1.txt
C:\Folder\Subfolder\2.txt

$BackupDirs = "C:\Folder"

Subfolder and 2.txt get copied
1.txt does not appear in the zip file or the staging folder during execution

keine Methode mit dem Namen "op_Addition"

Habe das Skript eben mal unter Windows 10 auf einem Netzlaufwerk getestet. Powershell sagt:

PreCheck was good, so start with Backup
Calculate Size and check Files
Failed to Measure Backupdir
Fehler beim Aufrufen der Methode, da [System.IO.FileInfo] keine Methode mit dem Namen "op_Addition" enthält. System.Management.Automation.CmdletInvocationException: Die angegebene Methode wir
d nicht unterstützt. ---> System.Management.Automation.PSNotSupportedException: Die angegebene Methode wird nicht unterstützt.
   bei Microsoft.PowerShell.Commands.SetPSBreakpointCommand.ProcessRecord()
   bei System.Management.Automation.CommandProcessor.ProcessRecord()
   --- Ende der internen Ausnahmestapelüberwachung ---
   bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   bei System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
   bei System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
   bei System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc() System.Management.Automation.CmdletInvocationException: Die angegebene Methode wird nicht unterstützt. ---> Syst
em.Management.Automation.PSNotSupportedException: Die angegebene Methode wird nicht unterstützt.

Der Fehler passiert in dem Block ab Zeile 191:

$Files+= Get-ChildItem -LiteralPath $Backup  | 
            ForEach-Object -Process { Add-Member -InputObject $_ -NotePropertyName "ParentFullName" -NotePropertyValue ($_.FullName.Substring(0, $_.FullName.LastIndexOf("\" + $_.Name))) -PassThru -ErrorAction SilentlyContinue } |
            Get-ChildItem -Attributes !D -ErrorVariable +errItems -ErrorAction SilentlyContinue
            $BackupDirFiles.Add($Backup, $Files)

Mehr erfahre ich da leider nicht ... was könnte ich tun? So fürchterlich viele Additionen kommen in dem Block ja nicht vor, und alle gibt es auch im darüber liegenden Block. Sehr seltsam.

Automated script start

How can i make the script runs once a day?
System is Win10.
Is the backup automaticly zipped? I prefer it unzipped.
Greetings
Andreas

Wrong order with staging

Files are copied to the destination folder.
Then they get zipped to stagingPath.
And then the zip is getting moved again to destination.

I think it is supposed to copy the files first to staging,zip them and then copy to the destination.

Failed to Measure Backupdir

Hi,

ich bekomme leider einen Fehler. Eine Idee wo mein Fehler ist? Nutze die neuste Version.

Failed to Measure Backupdir
Fehler beim Aufrufen der Methode, da [System.IO.FileInfo] keine Methode mit dem Namen “op_Addition” enthält. Fehler beim Aufrufen der Methode, da [System.IO
.FileInfo] keine Methode mit dem Namen “op_Addition” enthält.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.