Windows

Disk2VHD 定時備份腳本

  • July 29, 2019

我正在使用 Disk2VHD 使用這種簡單的備份腳本。我想稍微更改一下,以便檢查 C 盤驅動器的使用情況並將其與 F 盤進行比較,因此只有在 F 上沒有足夠的可用磁碟空間時才會刪除舊圖像。

目前,當已創建超過 4 個時,它會刪除舊圖像。

REM
REM A simple backup system using disk2vhd
REM
REM version 1.3, by J.E.B., 2011-02-22
REM
REM requires 'disk2vhd.exe' to be in the path
REM

setLocal EnableDelayedExpansion

REM "DRIVES" can be one drive identifier with colon, multiple separated by spaces,
REM or asterisk for all.  
REM "DEST" can be a drive letter or a UNC.

SET DRIVES="C:"
SET DEST="F:"

REM Keep most recent 4 VHD files in DEST, delete the rest

for /f "skip=4 tokens=* delims= " %%a in ('dir/b/o-d %DEST%\*.VHD') do (
del %DEST%\%%a
)

REM Backup to VHD

C:
cd \
DISK2VHD %DRIVES% %DEST%\%COMPUTERNAME%--%date:~-10,3%%date:~-7,2%%date:~-4,4%.VHD

EXIT /B n

這是 - 一個工作腳本!

# Null all the values
$Cdisk = $null
$Fdisk = $null
$CdiskCapacity =  $null
$CdiskFree =  $null
$CdiskUSed =  $null

#This function is called to determine the used space on the C: drive
function UsedDiskSpace() {
$Cdisk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'" | Select-Object Size,FreeSpace
$CdiskCapacity = $Cdisk.size/1073741824
$CdiskFree = $Cdisk.freespace/1073741824
$CdiskUSed = $CdiskCapacity-$CDiskFree
return $cdiskUsed
}

#This function is called repeatedly until the space on the F: drive is greater than the used space on the C: drive
function FreeDiskSpace() {
$Fdisk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='F:'" | Select-Object Size,FreeSpace
$Fdisk = $Fdisk.freespace/1073741824
return $Fdisk
}

#This function will simply delete the oldest file in the root of the F: drive
Function DelVHD {
Get-ChildItem F:\ | Sort CreationTime | Select -First 1 | Remove-Item -force -Recurse
}

#Create the VHD - pass $true to run the Disk2VHD program hidden; $False for visible. First run should be false to allow agreement of EULA.!
Function CreateVHD($Hidden) {
$filename = (get-date -uformat %d%b%y) + "_"  + $Env:COMPUTERNAME + ".vhd"
$filename = "F:\"+$Filename
   If ($Hidden -eq $True){
       start-process -WindowStyle Hidden c:\disk2vhd.exe -argumentlist 'c:', $filename # The .\ assumes disk2vhd is in the same folder as this script;
   }
       ElseIf ($Hidden -eq $False){c:\disk2vhd.exe c: $filename # The .\ assumes disk2vhd is in the same folder as this script;
   }
}

#This loop kicks everything off - it gets the free disk space, deletes files one at a time on F: as required and then creates the VHD when there is sufficient disk space freed up.
Do {
$c = useddiskspace
$f = freediskspace


if ($f -lt $c) {

write-host "Space used on C: = "$c
write-host "Free space on F: = "$f
write-host "Not enough free space on F: Drive. Deleting oldest image"
DelVHD
}
}
until ($f -gt $c)

write-host "Enough free space on F:\ found...creating latest VHD"
CreateVHD $true #NOTE - Run with $False so the Disk2VHD window is visible at least the first time in order to accept the EULA

引用自:https://serverfault.com/questions/722718