PowerShell + Robocopy: Daily Backup to a Password-Protected NAS

スポンサーリンク
PowerShell + Robocopy: Daily Backup to a Password-Protected NAS File Operations
スポンサーリンク

My C drive is covered by system image backups, but I realized the data piling up on drive D had no backup at all. So I set up a backup to my home NAS.

I could have dragged all of drive D onto the NAS by hand, but the data changes a little all the time, and doing that every time is clumsy. Instead I wrote a PowerShell backup script around robocopy.

Short answer: save the NAS password in Windows Credential Manager with cmdkey, mirror the drive with robocopy /MIR, and make the script refuse to run when the source drive is missing, empty included, so a dead drive can’t wipe the backup. Below is the full script (feel free to use it) and a Task Scheduler setup that runs it daily.

What the script does

  • Runs robocopy from the source ($srcFolder) to the destination ($dstFolder). Here the source is drive D and the destination \\192.168.1.253\backup\D-drive. Change both for your setup
  • The NAS user name and password are not in the script; they’re saved in Windows Credential Manager. Run this once in PowerShell with your own NAS address and user name. With nothing after /pass, it asks for the password, so the password never shows on screen. If the script can’t reach the NAS log folder, for example because no credentials are saved, it stops without copying
cmdkey /add:192.168.1.253 /user:backupper /pass
  • Checks whether it’s running as administrator and, if not, restarts itself as administrator
  • Writes robocopy’s output to a log in a log folder. $logFolder sets the folder, $logFile the file name (yyyy-mm-dd_datacopy.log). Create the log folder beforehand
  • Deletes logs older than a set number of days (93 here, about three months)
  • After robocopy, removes the hidden and system attributes from the destination folder. Copying from a drive root (D:\) makes the destination folder hidden; details in robocopy destination folder hidden: cause and fix
  • Reports an error when robocopy’s exit code is 8 or higher, which means some files failed to copy. What each code means: robocopy exit codes explained

robocopy options

The options are /MIR /DCOPY:DAT /COPY:DAT /IT /B /XD $excluded /log+:"$logFile" /np /R:3 /W:3.

  • /MIR makes the destination identical to the source. Files missing from the source are deleted from the destination, so if drive D is missing or empty, the NAS backup would be wiped too. That’s why the script stops in those cases
  • /DCOPY:DAT copies data, attributes and timestamps for directories
  • /COPY:DAT does the same for files. /COPYALL instead gave me error 1314 (0x00000522), “A required privilege is not held by the client”, while copying NTFS security to the NAS. /COPYALL also copies security information, and a NAS that manages permissions separately from the PC can’t take it. Within one domain it might work (not tested)
  • /IT also copies files whose only difference is their attributes (“tweaked” files)
  • /B runs in backup mode, which can copy files even without access permission to them. That’s why the script needs an administrator
  • /XD $excluded skips the listed folders: $RECYCLE.BIN (Recycle Bin) and System Volume Information at the drive root
  • /log+:”$logFile” appends the output to $logFile
  • /np hides the per-file percentage, which would otherwise flood the log
  • /R:3 retries a failed copy 3 times. The default is 1,000,000, which only wastes time
  • /W:3 waits 3 seconds before each retry. The default is 30 seconds

The script

Only three lines need changing: $srcFolder, $dstFolder, $logFolder.

# ============================================================
#  Mirror drive D to the NAS (revised 2026-11-08)
#  Changes from the old version:
#   1. No password in the script. The NAS credentials come from
#      Credential Manager (saved with cmdkey).
#   2. Stop if D: is missing, so /MIR cannot wipe the NAS backup. Same if D: is empty.
#   3. Skip $RECYCLE.BIN, System Volume Information.
#   4. (Snapshots / recycle bin on the NAS side are set up on the NAS.)
#   5. Report robocopy errors.
#  Uses /B, so it runs as administrator (reopens itself elevated).
# ============================================================

# If not running as administrator, reopen as administrator
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Host "Restarting as administrator..."
    Start-Sleep -Seconds 2
    Start-Process powershell.exe -Verb RunAs -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File ""$PSCommandPath"""
    exit
}

$srcFolder = "D:\"
$dstFolder = "\\192.168.1.253\backup\D-drive"
$logFolder = "\\192.168.1.253\backup\backup-tools\D-drive-robocopy\log"
$logFile   = Join-Path $logFolder "$(Get-Date -Format 'yyyy-MM-dd')_datacopy.log"

function Stop-WithMessage($msg) {
    Write-Host $msg -ForegroundColor Red
    Read-Host "Press the Enter key"
    exit 1
}

# --- Safety check 1: can we reach the NAS? (stops here if no credentials are saved)
if (-not (Test-Path -LiteralPath $logFolder)) {
    Stop-WithMessage "Cannot connect to the NAS: $logFolder - check that the NAS credentials are saved in Credential Manager."
}

# --- Safety check 2: D: must exist, with files in it
$excluded = @('$RECYCLE.BIN', 'System Volume Information')
if (-not (Test-Path -LiteralPath $srcFolder)) {
    Stop-WithMessage "D: not found. Exiting without copying to protect the NAS backup."
}
$items = @(Get-ChildItem -LiteralPath $srcFolder -Force -ErrorAction SilentlyContinue | Where-Object { $excluded -notcontains $_.Name })
if ($items.Count -eq 0) {
    Stop-WithMessage "D: is empty. Exiting without copying to protect the NAS backup."
}

# --- Mirror, then clear the hidden/system attributes on the destination folder
robocopy $srcFolder $dstFolder /MIR /DCOPY:DAT /COPY:DAT /IT /B /XD $excluded /log+:"$logFile" /np /R:3 /W:3
$rc = $LASTEXITCODE
attrib -s -h "$dstFolder"

# --- Remove logs older than 93 days
Get-ChildItem -LiteralPath $logFolder -Filter "*.log" |
    Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-93) } |
    ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force }

# --- Show the result. robocopy exit code 8+ means errors
if ($rc -ge 8) {
    Stop-WithMessage "Some files were not transferred. robocopy code: $rc, log: $logFile"
}
Write-Host "Done. robocopy code: $rc, log: $logFile" -ForegroundColor Green
Read-Host "Press the Enter key"

Run it daily with Task Scheduler

Running it by hand means forgetting, so I registered it in Task Scheduler. Open PowerShell with “Run as administrator” and paste this (change the script path). It runs daily at 12:30, and if the PC was off at that time, it runs the next time the PC starts.

$a = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "D:\backup-scripts\backup-d-to-nas.ps1"'
$t = New-ScheduledTaskTrigger -Daily -At 12:30
$p = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Highest
$s = New-ScheduledTaskSettingsSet -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Hours 12)
Register-ScheduledTask -TaskName 'Back up drive D to NAS' -Action $a -Trigger $t -Principal $p -Settings $s -Force
  • -RunLevel Highest is “Run with highest privileges”: it runs as administrator, so /B works without a UAC prompt
  • -LogonType Interactive runs only while you’re logged on, because the NAS credentials in Credential Manager belong to the logged-on user
  • -StartWhenAvailable is “Run task as soon as possible after a scheduled start is missed”
  • -NonInteractive keeps the task from waiting forever at the final “Press the Enter key” prompt. That prompt then prints a harmless “NonInteractive mode” error at the end of the output; the exit code is still correct (0 on success, 1 when it stops)

Notes

  • You need an environment where PowerShell scripts are allowed to run
  • With a drive root (such as D:) as the source, the destination folder can end up hidden and system, so Explorer doesn’t show it. The script clears that, and the cause is explained in robocopy destination folder hidden: cause and fix

Revision history

2024/02/08 First version
2026/11/08 Password moved to Credential Manager. Added safety checks, folder exclusions, error detection and daily runs with Task Scheduler

コメント

Copied title and URL