Skip to content

Commit ab1c4ec

Browse files
authored
BackupScript release 1.0.0
1 parent 1dcb6a6 commit ab1c4ec

13 files changed

+517
-0
lines changed

7z.dll

1.81 MB
Binary file not shown.

7z.exe

549 KB
Binary file not shown.

LICENSE

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
7zip LICENSE - https://www.7-zip.org/license.txt
2+
13
GNU LESSER GENERAL PUBLIC LICENSE
24
Version 2.1, February 1999
35

README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# BackUp Script
2+
3+
**English | [Русский](docs/ru/Readme_ru.md)**
4+
5+
Latest version: **[Download](https://github.com/We0M/BackupScript/releases/download/1.0.0/En_BackUp_Script.zip)**
6+
7+
## Actions after downloading
8+
9+
1. Unzip to a convenient location.
10+
2. Open **`backup_script_en.ps1`** and customize it for yourself. Almost all parameters have a description, **[below are some aspects](#additional-information)** that may not be entirely obvious.
11+
3. In **`Task Scheduler`** create a new task with the action **`Start a program`**, in the **`Program/script`** field, enter:
12+
```cmd
13+
Powershell
14+
```
15+
- In the **`Add arguments`** field, enter:
16+
```Powershell
17+
-ExecutionPolicy RemoteSigned -File "%userprofile%\Desktop\BackupScript\backup_script_ru.ps1"
18+
```
19+
> [!NOTE]
20+
>I added the path to the file in the arguments as an example, but you must specify the full path to the folder with the script there! The path specified in the example leads to the `BackupScript` folder on the desktop. **`%userprofile%`** - macro for accessing the user folder
21+
22+
> [!CAUTION]
23+
> Check if everything was done correctly by forcing the task. To do this, in the task scheduler, select the task you created and click `Run`, or right-click on this task and click `Run`.
24+
25+
---
26+
27+
## Additional information
28+
29+
- ### Date
30+
To use backup more often than once a day, there are 2 options:
31+
- update the data in the archive, no action is required for this. In this case, only the data that has changed since the previous backup of the same day will be added;
32+
- if separate archives are required, you need to change the date format in the variable `$date = Get-Date -Format "yyyy_MM_dd"` to `$date = Get-Date -Format "yyyy_MM_dd_HH_mm"` i.e. add hours and minutes.
33+
34+
- ### [List sources and exclusions](docs/Sources_and_Exclusions.md)
35+
- ### [Add task to `Task Scheduler`](docs/Task_Scheduler.md)
36+
37+
---

backup_script_en.ps1

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#############################
2+
### BackUp Script by WeoM ###
3+
#############################
4+
5+
$version = "1.0"
6+
$scriptName = "BackUp Script $version by WeoM"
7+
8+
#Load lib WinForms
9+
Add-Type -AssemblyName System.Windows.Forms
10+
11+
#Create message
12+
$result = [System.Windows.Forms.MessageBox]::Show("Need to make a backup. Click 'Ok' when you are ready.", "$scriptName", [System.Windows.Forms.MessageBoxButtons]::OKCancel, [System.Windows.Forms.MessageBoxIcon]::Information)
13+
14+
function Get-Timestamp {
15+
return (Get-Date).ToString("dd.MM.yyyy HH:mm:ss")
16+
}
17+
18+
if($result -eq [System.Windows.Forms.DialogResult]::OK) {
19+
# get the path to folder where the executable script is located: source.txt exclude.txt 7z.exe 7z.dll
20+
$path = $PSScriptRoot
21+
$7z = Join-Path -Path $path -ChildPath "7z.exe"
22+
# WARNING! in source.txt and exclude.txt files it is necessary to use full paths because of the -spf2 key
23+
# in source.txt we add folders and files that are added to the backup
24+
$sourceList = Join-Path -Path $path -ChildPath "source.txt"
25+
# exclusions are added to exclude.txt
26+
$excludeList = Join-Path -Path $path -ChildPath "exclude.txt"
27+
# the folder where the backups will be saved
28+
$target = "D:\BackupFolderName\"
29+
# current date in format 2024_01_01
30+
$date = Get-Date -Format "yyyy_MM_dd"
31+
# name of the resulting file
32+
$filename = "backup_$date.7z"
33+
# optionally you can add a password to the archive, to do this you need to enter the desired password between ""
34+
$pwd = ""
35+
36+
$check = $true
37+
$counter = 0
38+
while($check -and $counter -le 4) {
39+
# verification is necessary because of the -mhe key, otherwise the archive will be without a password but with encrypted headers.
40+
if(-not $pwd) {
41+
Write-Host "`n$(Get-Timestamp) Create a backup without a password" -ForegroundColor Magenta
42+
& $7z a -t7z (Join-Path -Path $target -ChildPath $filename) -bt -mx5 -ssw -snh -snl -ssp -spf2 @$sourceList -xr@"$excludeList" -scrcSHA256
43+
} else {
44+
Write-Host "`n$(Get-Timestamp) Create a backup with a password" -ForegroundColor DarkGreen
45+
& $7z a -t7z (Join-Path -Path $target -ChildPath $filename) -bt -mx5 -ssw -snh -snl -ssp -spf2 -p"$pwd" -mhe @$sourceList -xr@"$excludeList" -scrcSHA256
46+
}
47+
48+
# check archive and data integrity
49+
Write-Host "`nCheck archive and data integrity. Wait..." -ForegroundColor Blue
50+
$result = & $7z t (Join-Path -Path $target -ChildPath $filename) -p"$pwd"
51+
if ($result -like "*Everything is Ok*") {
52+
foreach ($line in $result) {
53+
Write-Host $line -ForegroundColor DarkYellow
54+
}
55+
Write-Host "`n$(Get-Timestamp) backup successfully created! `nFile name: $filename `nPath: $target " -ForegroundColor Green
56+
Write-Host "This window will close in 5 seconds..."
57+
Start-Sleep -Seconds 5
58+
$check = $false
59+
} else {
60+
Write-Host "`n$(Get-Timestamp) ERROR:" -ForegroundColor Red
61+
foreach ($line in $result) {
62+
Write-Host $line -ForegroundColor Red
63+
}
64+
}
65+
66+
$counter += 1
67+
68+
# if the archive could not be created in 5 attempts, the cycle ends
69+
if ($counter -gt 4) {
70+
$errorMessage = "`n$(Get-Timestamp) Failed to create archive after $counter attempts. Operation cancelled."
71+
Write-Host $errorMessage -ForegroundColor Red
72+
[System.Windows.Forms.MessageBox]::Show("$errorMessage", "$scriptName", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
73+
$check = $false
74+
}
75+
}
76+
} else {
77+
Write-Host "`n$(Get-Timestamp)Backup creation cancelled." -ForegroundColor Red
78+
Write-Host "This window will close in 5 seconds..."
79+
Start-Sleep -Seconds 5
80+
}

backup_script_ru.ps1

7.2 KB
Binary file not shown.

docs/Sources_and_Exclusions.md

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# List sources and exclusions
2+
3+
Let's assume you have the following folder structure:
4+
```
5+
C:\data\
6+
├── important\
7+
│ ├── docs\
8+
│ │ ├── .exclude\
9+
│ │ ├── file5.tmp
10+
│ │ └── file6.tmp
11+
│ ├── .exclude\
12+
│ ├── file1.txt
13+
│ └── file2.txt
14+
└── temp\
15+
├── .exclude\
16+
├── file3.tmp
17+
└── file4.tmp
18+
```
19+
20+
> [!CAUTION]
21+
> All paths must be full, not absolute, i.e. the path must start with a drive letter.
22+
23+
24+
## List file source.txt
25+
26+
1. **File format**:
27+
28+
In the file, you can specify paths to files and folders that you want to archive, and also add comments, starting the line with `#`. Each path must be on a separate line.
29+
For example:
30+
```
31+
C:\data\important\file1.txt
32+
C:\data\important\file2.txt
33+
# this line is ignored by 7-Zip
34+
C:\data\important\docs\
35+
```
36+
37+
> [!NOTE]
38+
> If the path contains spaces, it must be enclosed in quotation marks:
39+
> ```
40+
> "C:\path with spaces\file1.txt"
41+
> ```
42+
43+
2. **Templates**:
44+
45+
You can use wildcards (`*` and `?`) to specify file groups:
46+
- `*` - matches any number of characters (including zero).
47+
```md
48+
`C:\path\to\*.txt` includes all files with the extension `.txt` in the specified folder.
49+
```
50+
- `?` - matches any single character.
51+
```md
52+
`C:\path\to\file?.txt` matches `file1.txt`, `file2.txt`, but not `file10.txt`.
53+
```
54+
You can use `**` to recursively search for files in all subdirectories.
55+
```md
56+
`C:\path\to\**\*.jpg` includes all `.jpg` files in the specified folder and all its subdirectories.
57+
```
58+
59+
## exclude.txt
60+
61+
To exclude individual files or folders that you do not want to save in the backup, use the `exclude.txt` file.
62+
63+
### Examples of exceptions:
64+
65+
1. **Single file exclusion**:
66+
```md
67+
C:\data\important\file1.txt
68+
```
69+
70+
2. **Exclude all files of a certain type**:
71+
```md
72+
C:\data\temp\*.tmp
73+
```
74+
75+
3. **Exclude a specific folder**:
76+
```md
77+
C:\data\temp\
78+
```
79+
80+
4. **Exclude all folders of a specific name**:
81+
```md
82+
*.exclude\*
83+
```
84+
85+
---
86+
87+
## Example of use
88+
89+
If you want to archive the entire `data` folder, excluding the `temp` folder, all `.tmp` files in all folders, as well as the `.exclude` folders, for this:
90+
- Add a line to the `source.txt` file
91+
```
92+
C:\data\
93+
```
94+
- Add lines to the `exclude.txt` file
95+
```
96+
C:\data\temp\ # excludes temp folder
97+
*.tmp # excludes all files with the .tmp extension in all folders
98+
*.exclude\* # excludes all folders named .exclude and their contents in all folders
99+
```
100+
101+
As a result, the following structure will be preserved:
102+
103+
```
104+
C:\data\important\
105+
├── docs\
106+
│ ├── file5.tmp
107+
│ └── file6.tmp
108+
├── file1.txt
109+
└── file2.txt
110+
```
111+
112+
[<- return to README](/README.md)
113+
114+
---
115+

docs/Task_Scheduler.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Add task to `Task Scheduler`
2+
3+
To add a task to the **Task Scheduler** in Windows, follow these steps:
4+
5+
To create a more advanced task in Task Scheduler, follow these detailed steps:
6+
7+
### 1. **Open Task Scheduler:**
8+
- Press `Windows + R` to open the Run dialog.
9+
- Type `taskschd.msc` and hit `Enter` to open Task Scheduler.
10+
11+
### 2. **Create a New Task:**
12+
- In the left pane, select **Task Scheduler Library** to see existing tasks.
13+
- In the **Actions** pane on the right side, click **Create Task** (not **Create Basic Task**). This gives you more control over the task's configuration.
14+
15+
### 3. **General Tab:**
16+
- **Name**: Enter a descriptive name for your task.
17+
- **Description**: (Optional) Provide a description for the task.
18+
- **Security options**:
19+
- Choose the user account under which the task will run.
20+
- If you want the task to run with elevated privileges (as administrator), check **Run with highest privileges**.
21+
- **Configure for**: Select the version of Windows you're using, or leave it set to **Windows 10** (default).
22+
23+
### 4. **Triggers Tab:**
24+
Triggers define when the task will run. You can set multiple triggers for one task.
25+
- Click **New** to create a trigger.
26+
- **Begin the task**: Choose when the task should trigger. Options include:
27+
- **On a schedule**: Daily, Weekly, Monthly, etc.
28+
- **At logon**: When you log into Windows.
29+
- **At startup**: When Windows starts.
30+
- **On an event**: When a specific system event occurs.
31+
- **On idle**: When the system is idle.
32+
- Once you configure the trigger, click **OK**.
33+
34+
### 5. **Actions Tab:**
35+
Actions define what the task will actually do once triggered.
36+
- Click **New** to define an action.
37+
- **Action**: Select **Start a program** (this is the most common option).
38+
- In the **Program/script** field, enter:
39+
```cmd
40+
Powershell
41+
```
42+
- In the **`Add arguments`** field, enter:
43+
```Powershell
44+
-ExecutionPolicy RemoteSigned -File "%userprofile%\Desktop\BackupScript\backup_script_ru.ps1"
45+
```
46+
> [!NOTE]
47+
>I added the path to the file in the arguments as an example, but you must specify the full path to the folder with the script there! The path specified in the example leads to the `BackupScript` folder on the desktop. `%userprofile%` - macro for accessing the user folder
48+
49+
- Once you're done, click **OK**.
50+
51+
### 6. **Conditions Tab:**
52+
Conditions define additional requirements for the task to run. These are optional, but helpful if you want the task to have specific conditions:
53+
- **Start the task only if the computer is idle for**: Specifies how long the computer must be idle before the task starts.
54+
- **Stop if the computer switches to battery power**: Useful for laptops to conserve battery life.
55+
- **Wake the computer to run this task**: Check this if you want the task to run even when the system is in sleep mode.
56+
- Configure these options as per your needs, then click **OK**.
57+
58+
### 7. **Settings Tab:**
59+
The Settings tab allows you to configure additional behaviors for the task.
60+
- **Allow task to be run on demand**: This lets you manually start the task if desired.
61+
- **If the task fails, restart every**: Set up a retry interval and how many attempts should be made if the task fails.
62+
- **Stop the task if it runs longer than**: Useful for long-running tasks to avoid hanging processes.
63+
- **If the task is already running, then the following rule applies**: You can specify whether to run a new instance or wait for the existing task to finish.
64+
- After configuring, click **OK**.
65+
66+
### 8. **OK and Save the Task:**
67+
- After completing all the tabs, click **OK** to save the task.
68+
- If prompted, enter your password or provide appropriate credentials if the task is set to run with elevated privileges.
69+
70+
### 9. **Verify the Task:**
71+
- Once created, your task will appear in the **Task Scheduler Library**.
72+
- You can **right-click** the task and select **Run** to manually trigger it or **Properties** to edit it.
73+
74+
[<- return to README](/README.md)
75+
76+
---

docs/ru/Readme_ru.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# BackUp Script
2+
3+
**[English](/README.md) | Русский**
4+
5+
Последняя версия: **[Скачать](https://github.com/We0M/BackupScript/releases/download/1.0.0/Ru_BackUp_Script.zip)**
6+
7+
## Действия после скачивания
8+
9+
1. Разархивировать в удобное место.
10+
2. Откройте **`backup_script_ru.ps1`** и настройте под себя. Практически все параметры имеют описание, **[ниже рассмотрены](#дополнительная-информация)** аспекты, которые могут быть не совсем очевидны.
11+
3. В **`планировщике заданий`** создайте новую задачу с действием **`Запуск программы`**, в поле **`Программа или сценарий`** введите:
12+
```cmd
13+
Powershell
14+
```
15+
в поле **`Добавить аргументы`** введите:
16+
```Powershell
17+
-ExecutionPolicy RemoteSigned -File "%userprofile%\Desktop\BackupScript\backup_script_ru.ps1"
18+
```
19+
> [!NOTE]
20+
> Путь к файлу в аргументах я добавил для примера, вы же должны там указать полный путь к папке со скриптом! Указанный в примере путь ведёт к папке `BackupScript` на рабочем столе. **`%userprofile%`** - макрос для доступа к папке пользователя
21+
22+
> [!CAUTION]
23+
> Проверьте, всё ли правильно сделали, выполнив принудительно задачу. Для этого в планировщике заданий выделите созданную вами задачу и нажмите `Выполнить`, либо нажмите ПКМ по этой задаче и нажмите `Выполнить`.
24+
25+
---
26+
27+
## Дополнительная информация
28+
29+
- ### Date
30+
Для использования бекапа чаще чем раз в сутки есть 2 варианта:
31+
- просто обновить данные в архиве, для этого никаких действий не требуется. В этом случае будут добавлены только данные, которые изменились с момента предыдущего бекапа того же дня;
32+
- если же требуются отдельные архивы, для этого необходимо изменить формат даты в переменной `$date = Get-Date -Format "yyyy_MM_dd"` на `$date = Get-Date -Format "yyyy_MM_dd_HH_mm"` т.е добавить часы и минуты.
33+
34+
- ### [Список источников и исключения](Sources_and_Exclusions_ru.md)
35+
- ### [Добавление задачи в `Планировщик заданий`](Task_Scheduler_ru.md)
36+
37+
---

0 commit comments

Comments
 (0)