GithubHelp home page GithubHelp logo

postasze / disk-cloning-powershell-script Goto Github PK

View Code? Open in Web Editor NEW
0.0 1.0 0.0 2.01 MB

Powershell script for automatic, periodic task of cloning/backup of disk drives/partitions/os in Windows

PowerShell 100.00%

disk-cloning-powershell-script's Introduction

Disk-Cloning-Powershell-Script

This is a convenient Powershell script for performing automatic, scheduled, periodic tasks of cloning/backup procedures between specified disk drives/partitions/operating systems, working in Windows.
This script works well in Powershell version 5.1 and it was tested in Windows 10 and Windows 11 without problems.
This script uses Macrium Reflect program, version 8.1, for performing direct sector to sector copying.
This script is entirely free to use and modify, of course.

Currently, this script is set to make a full clone/backup of main disk drive with letter C to an external, attached USB disk drive which has enough capacity to contain all used space of main disk drive.
Also, this script is currently set to make a full clone/backup of main disk drive automatically, periodically every week. This script makes 3 cloning/backup attempts. On Friday, Saturday, Sunday at 22:00 (10:00 PM). If one cloning/backup procedure was successfully performed in the current week then next attempts in the current week are not performed.
If no external USB disk was inserted into the computer and if no cloning/backup procedure was performed in the current week then it is no problem, the script will make next attempts in the next weeks.
This script can be also launched manually to perform cloning/backup procedure right now without the need for waiting for the next scheduled attempts to be made by this script in this week.

This script can be easily modified to work in different periods like every day or every month.
This script can also be modified for another cloning/backup purposes, like for using other programs than Macrium Reflect or to make clones/backups without 3rd party programs or to clone disks/partitions between external USB disks or internal disks/partitions connected through SATA adapters.

This is a standalone working script which creates a scheduled cloning/backup task, which in turn launches the same script periodically in specified time intervals like every week.
This script ensures that there is only 1 such scheduled task running periodically at a time. This scheduled task can be viewed in Task Scheduler App in Windows.
This script should be launched with administrator's privileges and it also creates scheduled task, which is set to be run with administrator's rights.

This script is quite careful about performing cloning/backup procedure to not cause any problems like format/erase of wrong data. If script detects any problem or issue like mismatched disk drives IDs then this script immediately stops its cloning/backup procedure and displays warning/error messages in the console.
For instance Main Windows disk/partition with C letter is never selected as cloning/backup target in this script.
This script also logs all relevant information about every cloning/backup attempt in a log file, currently set to this full path.
C:\Users$UserName\Documents\Reflect\cloning_info_log.txt In this file information about previous cloning/backup procedures can be viewed.
This script remembers unique IDs of previously used disks drives in previous cloning/backup procedures and selects for the current cloning/backup procedure disk drives which were least recently used. This script also selects with higher preference disk drives that were previously used for cloning/backup procedure than disk drives that were never used for this procedure before.

The script is in the file disk_cloning_script.ps1. There is also disk_cloning_script_polish_version.ps1 which is the same script but displays information written in polish language.
Results of the working of this script can be viewed in folders with screens

In this folder
C:\Users$UserName\Documents\Reflect
there are located xml files used by Macrium Reflect program, which contain important information about cloning/backup procedures. These xml files can be easily generated by Macrium Reflect program when there is a need of using different disk drives with different unique IDs. There is no need to modify these xml files, though. Because this script tries to handle them automatically and has an option to copy disk cloning/backup information from previously used xml files to new xml files when there is newly used disk drives with new, unique ID.

The unique disk drives IDs used by this script and also used by Diskpart utility and Macrium Reflect program are identical to disk drives IDs obtained by below Powershell command. The property Signature represents this unique ID of disk drive. However, below command returns decimal number representing this unique disk ID. In the script this decimal number is converted to hexadecimal number with 8 digits which is used by Diskpart utility and Macrium Reflect program.

Get-WmiObject -Class Win32_DiskDrive | select Description, DeviceID, MediaType, Model, Partitions, Signature, Size, Status

Currently, this script is developed to work with disks with MBR partition tables. This script can be modified to handle disks with GPT partition tables too.

Below is a more detailed description of algorithm of operations performed by this script for automatic, periodic cloning/backup procedures.

  1. Saving/logging the information about current cloning/backup attempt to log file with path C:\Users$UserName\Documents\Reflect\cloning_info_log.txt
  2. Verifying if this script was correctly launched with administrator privileges. It should have administrator rights to perform its procedures correctly
  3. Displaying in the console window a lot of detailed information about all disk drives connected to the computer with information about their partitions and volumes inside these disk drives
  4. Verifying if there already exists scheduled, automatic task to launch this script every week. If such task doesn't exist yet in Task Scheduler App in Windows then this script creates this scheduled task to run this script periodically every weekend.
  5. Verifying if there was already done successfully a cloning/backup attempt in this week before. If yes then this script instantly stops this attempt. For example if one cloning/backup attempt was done successfully in Friday then attempts in Saturday and Sunday won't be performed
  6. Searching for the main disk drive with C letter which will used as source disk drive for cloning/backup procedure.
  7. Calculating the size of main, source disk drive. Calculating the size of used space and of free space for cloning/backup procedure
  8. Searching for all external disk drives connected/attached to the computer through the USB port, which can be used as target disk drives for cloning/backup procedure.
  9. Selecting among these found external disk drives connected through the USB port the disk, which have enough space size to contain full clone of main, source disk drive.
  10. Verifying if there already exists xml file in this folder C:\Users$UserName\Documents\Reflect, such that they contain correct information about cloning/backup procedure, information like source and target disk IDs
  11. If correct xml files exist then this script selects newest xml file. If correct xml files don't exist then this script attempts to create a new xml from previously used xml files with correct source and target disk IDs
  12. Starting background services and programs of Macrium Reflect like ReflectMonitor.exe and ReflectUI.exe so that program Reflect.exe can do direct sector to sector copying stage of cloning/backup procedure
  13. Validating the correctness of cloning/backup procedure information written in xml file using Reflect.exe program
  14. Formatting/cleaning target disk drive connected to the computer through the USB port so that main, source disk can be copied into it without problems. Warning message is displayed for 30 seconds. If the user is near the computer then he/she can stop this formatting operation and stop the entire script by pressing any button.
  15. Main operation of this script. Performing sector to sector copying of data from main, source disk drive into external USB disk drive with enough space size to contain whole main, source disk drive
  16. Saving/logging the information about current cloning/backup result to log file with path C:\Users$UserName\Documents\Reflect\cloning_info_log.txt
  17. Stopping background services and programs of Macrium Reflect like ReflectMonitor.exe and ReflectUI.exe so that they don't waste computer's resources like RAM or CPU
  18. This script closes console window automatically after 5 minutes after finishing all other instructions in case someone would like to read the output of this script. Any button can be pressed to close console window instantly without waiting 5 minutes.

Below is a description of this Powershell script in polish language:



Program/skrypt do automatycznego klonowania dysków co określony okres czasu, obecnie jest ustawiony na co tydzień.

Automatyczne, okresowe zadanie klonowania dysków co tydzień. Ten skrypt podejmuje 3 próby klonowania na tydzień - w każdy piątek, sobotę i niedzielę o godzinie 22:00.
Jeśli któraś próba klonowania zakończy się powodzeniem w danym tygodniu to już nie są podejmowane kolejne próby klonowania w danym tygodniu. Wystarczy jedna procedura klonowania na tydzień.
Jeśli w którymś tygodniu nie będzie włożony zewnętrzny dysk twardy USB do klonowania to nic straconego, żaden problem. Program/skrypt będzie próbował robić klonowanie dysku w następnych tygodniach, w piątek, sobotę i niedzielę wieczorem. Nie musi być wykonywana procedura klonowania w każdy tydzień.

Można wkładać dowolne dyski twarde poprzez USB do komputera byleby tylko miały większy rozmiar niż zajęte miejsce w głównym dysku źródłowym.
Program/skrypt do klonowania dysku jest bardzo ostrożny tak, żeby nie spowodować żadnych problemów. Jak tylko jest jakiś problem to program/skrypt od razu zaprzestaje działania i wypisuje komunikat o problemie na ekran konsoli. Program/skrypt klonuje tylko główny dysk źródłowy tylko na jakiś zewnętrzny dysk podłączony poprzez USB o wystarczającym rozmiarze do zawarcia w sobie całego dysku źródłowego.
Program/skrypt zapamiętuje identyfikatory poprzednio używanych dysków docelowych w procedurach klonowania i w pierwszej kolejności wybiera ten docelowy dysk twardy, który był już używany wcześniej w procedurze klonowania, z większą preferencją od dysków twardych, które jeszcze nigdy nie były wykorzystane jako docelowe w procedurze klonowania.

Program/skrypt zapisuje informacje o wszystkich próbach i operacjach klonowania w poniższym pliku Można w nim sprawdzać, jaki był rezultat działania poprzednich prób/operacji klonowania C:\Users$UserName\Documents\Reflect\cloning_info_log.txt

Można uruchamiać ten program/skrypt klikając na niego prawym przyciskiem myszy i wybierając opcję "Uruchom jako administrator". Aczkolwiek nie trzeba już uruchamiać tego programu/skryptu ręcznie, bo ten program/skrypt jest uruchamiany automatycznie przez okresowe zadanie uruchamiające się w każdy piątek, sobotę i niedzielę o 22:00.
W tym folderze
C:\Users$UserName\Documents\Reflect
znajdują się pliki xml, używane przez program Macrium Reflect, zawierające ważne informacje o procedurze klonowania. Te pliki xml można zawsze łatwo wygenerować przez program Macrium Reflect, gdyby była potrzeba używania innych dysków twardych o innych identyfikatorach. Na ogół nie trzeba nic robić z tymi plikami xml, ten program/skrypt stara się zarządzać tymi plikami xml automatycznie i wybierać jak najlepszy i najbardziej aktualny. Program/skrypt ma też funkcjonalnosć kopiowania zawartości poprzednio używanego pliku xml do nowego pliku xml jeśli obecnie jest używany nowy dysk twardy z innym unikatowym identyfikatorem niż używane dotychczas.

W folderze ze screenami można zobaczyć rezultat działania programu/skryptu.

Poniżej jest bardziej szczegółowy opis algorytmu działania tego programu/skryptu do automatycznego klonowania dysku twardego co określony okres czasu:

  1. Zapisywanie informacji o obecnej próbie klonowania do pliku C:\Users$UserName\Documents\Reflect\cloning_info_log.txt
  2. Sprawdzanie czy ten program/skrypt został uruchomiony z uprawnieniami administratora, bo powinien mieć uprawnienia administratora do prawidłowego wykonania procedury klonowania
  3. Wyświetlanie w ekranie konsoli szczegółowych informacji o wszystkich dyskach twardych podłączonych do komputera oraz informacji o partycjach i woluminach wewnątrz tych dysków twardych
  4. Sprawdzanie czy już istnieje automatyczne, okresowe zadanie do uruchamiania tego programu/skryptu do klonowania dysku w każdy weekend. Jeśli takie okresowe zadanie nie istnieje to ten program/skrypt tworzy nowe, okresowe zadanie do uruchamiania tego programu/skryptu do klonowania dysku w każdy weekend.
  5. Sprawdzenie czy już wcześniej w tym tygodniu została wykonana procedura klonowania dysku z powodzeniem. Jeśli tak to program/skrypt od razu kończy tą obecną próbę klonowania. Np. jeśli w piątek wieczorem już został sklonowany dysk a program/skrypt uruchomi się jeszcze w sobotę i niedzielę wieczorem, więc na początku to sprawdza.
  6. Wyszukiwanie głównego dysku twardego na komputerze, który będzie dyskiem źródłowym dla procedury klonowania.
  7. Obliczanie rozmiaru głównego dysku twardego, obliczanie zajętej przestrzeni i wolnej przestrzeni głównego dysku źródłowego dla procedury klonowania
  8. Wyszukiwanie wszystkich zewnętrznych dysków twardych podłączonych poprzez port USB do komputera, które mogą być wykorzystane jako dyski docelowe w procedurze klonowania
  9. Wybieranie spośród znalezionych zewnętrznych dysków twardych podłączonych poprzez port USB do komputera, takich dysków twardych, które mają wystarczający rozmiar do zawarcia w sobie całego głównego dysku źródłowego w procedurze klonowania
  10. Sprawdzanie czy istnieją już pliki xml w tym folderze C:\Users$UserName\Documents\Reflect, takie pliki xml, które zawierają prawidłowe informacje o procedurze klonowania
  11. Jeśli już istnieją takie pliki xml to wybieranie najbardziej aktualnego takiego pliku xml, jeśli nie istnieją to tworzenie nowego pliku xml zawierającego prawidłowe informacje o procedurze klonowania.
  12. Uruchamianie usług Macrium Reflect działających w tle, tak żeby dało się uruchomić główny program Macrium Reflect do wykonania procedury klonowania.
  13. Weryfikowanie poprawności informacji o procedurze klonowania zapisanych w wybranym pliku xml za pomocą programu Macrium Reflect.
  14. Formatowanie/czyszczenie docelowego dysku twardego podłączonego poprzez port USB do komputera tak żeby można było sklonować na niego główny dysk źródłowy. Użytkownik, jeśli jest przy komputerze, może anulować tą operację w ciągu 30 sekund klikając dowolny klawisz
  15. Główna operacja programu/skryptu: Wykonywanie procedury klonowania z głównego dysku źródłowego na zewnętrzny dysk docelowy USB o wystarczającym rozmiarze.
  16. Zapisywanie informacji o rezultacie obecnej próby klonowania do pliku C:\Users$UserName\Documents\Reflect\cloning_info_log.txt
  17. Wyłączanie usług Macrium Reflect działających w tle, po to żeby nie zużywały niepotrzebnie pamięci/procesora komputera gdy nie są używane.
  18. Program/skrypt zamyka się automatycznie po 5 minutach po zakończeniu pozostałych operacji, na wypadek gdyby ktoś chciał jeszcze przeczytać tekst wygenerowany przez program/skrypt. Jeśli użytkownik jest przy komputerze to może nacisnąć dowolny klawisz żeby od razu wyłączyć to czarne okno konsoli z programem/skryptem

disk-cloning-powershell-script's People

Contributors

postasze avatar

Watchers

 avatar

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.