0
votes

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?

1
Sounds like there are no *.bak files in the backup directory. Wrap the Copy-Item command in a conditional, like so: if($LatestBackupFilename){ Copy-Item ... }Mathias R. Jessen
I dont think that is the issue as there is a .bak file in backup location. It states the error resides in line 8 - Copy-Item $LatestBackupFileName -Destination $WorkDir\AutomatedDbRefresh.bak -Forcesqllover2020

1 Answers

0
votes

It would appear that this is because $BackupDir references a file instead of a folder.

$BackupDir = "C:\SQL Installs\Backups\Full Backups\Sample_full.bak". In order for this to work $BackupDir would need to be something like $BackupDir = "C:\SQL Installs\Backups\Full Backups" After you do this you should be able to make this line work.
$LatestBackupFileName = (Get-ChildItem $BackupDir*.bak | sort LastWriteTime | select -last 1)