I need to create a PowerShell script that will copy my backup files from PROD server to restore it on DEV server on a monthly basis. Then I need to create a SQL Agent job with two steps. The first step will be to restore those copied files onto DEV Server. The second step will be to execute a SP that cleans up the redundant/inconsistent data.
So far this is the script I created
# begin set vars
$BackupDir = "C:\SQL Installs\Backups\Full Backups\Sample_full.bak" # where backups are stored
$WorkDir = "C:\SQL Installs\Backups\Test Backups" # where you are copying backup to
# end set vars
Set-Location $WorkDir
$LatestBackupFileName = (Get-ChildItem $BackupDir\*.bak | sort LastWriteTime | select -last 1)
Copy-Item $LatestBackupFileName -Destination $WorkDir\AutomatedDbRefresh.bak -Force
Here is the result output- showing that the path is null.
Set-Location $WorkDir
$LatestBackupFileName = (Get-ChildItem $BackupDir\*.bak | sort LastWriteTime | select -last 1)
Copy-Item $LatestBackupFileName -Destination $WorkDir\AutomatedDbRefresh.bak -Force
Copy-Item : Cannot bind argument to parameter 'Path' because it is null.
At line:8 char:11
+ Copy-Item $LatestBackupFileName -Destination $WorkDir\AutomatedDbRefr ...
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Copy-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CopyItemCommand
Can someone please advise on how to avoid this error and what I may need to fix in my script?
*.bak
files in the backup directory. Wrap theCopy-Item
command in a conditional, like so:if($LatestBackupFilename){ Copy-Item ... }
– Mathias R. JessenCopy-Item $LatestBackupFileName -Destination $WorkDir\AutomatedDbRefresh.bak -Force
– sqllover2020