3
\$\begingroup\$

I have a script and I was looking to have it reviewed to see where I should improve it.

Our need: We need to backup a folder every day to a specific USB drive. There may be multiple USB drives plugged into the computer. We need to ensure that it is only backing up to a specific drive.

Code:

function ex{exit}

#####################################
### Check PC for backup USB Drive ###
#####################################

$diskdrive = Get-WmiObject win32_diskdrive

foreach($drive in $diskdrive){
  $partitions = Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($drive.DeviceID.replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"

    foreach($part in $partitions){
        $name=$drive.model
        $vols = Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($part.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"

    foreach($vol in $vols){
       If($name -eq "General UDisk USB Device" ){
       $USBDisk=$vol.name
       }
     }
  }
}

if ( $USBDisk -eq $null ) {
[void][System.Windows.Forms.MessageBox]::Show("Custom Backup, Please Plug-In the USB Drive","USB Drive not found")
ex
}


###########################################
### Purge USB for data over 90 days old ###
###########################################

$limit = (Get-Date).AddDays(-90)

Get-ChildItem -Path $USBDisk -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $USBDisk -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

#########################
### Backup Custom DBs ###
#########################

# Import Assemblies
[void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")

$date = Get-Date -Format MMMM.d.yyyy
$backupFolder = "Backup_" + "$date" 

if ( $USBDisk -eq $null ) {
#[void][System.Windows.Forms.MessageBox]::Show("No USB Disk Found, Please Plug-In the USB Drive","USB Drive not found")
} 
else {
$Usbfreedisk =  ((Get-WmiObject win32_logicalDisk  | where { $_.DeviceID -eq $USBDisk }).FreeSpace /1gb -as [INT])
$FPBackup= Get-ChildItem -Recurse "C:\Folder" | Measure-Object -property length -sum
[int]$DataFilesize = ($FPBackup.sum / 1GB )

if ( $Usbfreedisk -lt $DataFilesize ) {
    [void][System.Windows.Forms.MessageBox]::Show("Your $USBDisk Drive don't have enough space, for backup we need $DatafileSize GB of free space.","Not Enough space")
    }
else {
    $testfolder = Test-Path "$USBDisk\$backupFolder" 
		if ( $testfolder -eq $true ) {
		[void][System.Windows.Forms.MessageBox]::Show("You already have backup folder $USBDisk\$backupFolder Please rename it or delete it before running the backup ","Backup Folder Exists")	
		}
	else{	
		mkdir "$USBDisk\$backupFolder"
		Robocopy "C:\Folder"  "$USBDisk\$backupFolder\CYA" /mir /r:2 /w:3
    if ($lastexitcode -eq 0){
            write-host "Robocopy succeeded"
            }
            else{
            write-host "Robocopy failed with exit code:" $lastexitcode
            }
        }
    }
} 

Please let me know if anyone needs any clarification on anything.

Thanks

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to Code Review! What happens when Robocopy fails for reasons you haven't caught? Is this acceptable? You spell usbdisk with different capitals at times, is this on purpose? What do you think of this practice yourself? \$\endgroup\$ – Mast Aug 13 at 14:04
  • \$\begingroup\$ @Mast Thank you very much for your response! The Robocopy is a good point. I can give that some consideration and make modifications. The USBDisk typos were not on purpose and I have updated them in my script. \$\endgroup\$ – RookieUser Aug 13 at 14:35
  • \$\begingroup\$ @Mast I just added in a catch for a failure. I'll have to consider what we would like to do if it does fail, but I figured that could be a start. \$\endgroup\$ – RookieUser Aug 13 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.