I'm currently working on a PowerShell script that migrates databases from one server to another. Part of the migration includes restoring the databases on the new server. I want to make this automation as dynamic as possible, so part of my script opens up a file browser window and allows the user to choose the location of where to backup the databases on the source server and new server.
This is an overview of the user input steps.
- Script obtains information on the source server and instance. (Stored in $server_instance)
- Script obtains information on the new server and instance of where the databases are being migrated to. (Stored in $new_server_instance)
- Script obtains the path of where to store the backup files on the source server. The script opens up a file explorer and stores the path in a variable. (Stored in $local_backup_path)
- Script obtains the path of where to store the backup files on the target server. The script opens up a file explorer and stores the path in a different variable. (Stored in $target_backup_path)
- Script performs the backup of the databases on the source server and copies the backup files from $local_backup_path to $target_backup_path.
- Script restores the databases on the new server from the $target_backup_path. This is the step where I am having an issue.
Here is an example of the paths and leads me to my actual question:
$local_backup_path = T:\PowerShell\Testing\backup
$target_backup_path = \\$target_server\T$\PowerShell\backups
I am running these commands to restore the databases on the new server from the recently migrated backup files:
Restore-SqlDatabase -ServerInstance $New_Server_Instance -Database $database -BackupFile "$target_backup_path\$database.bak"
Write-Host "$database has been restored on the new server"
This is problematic because of the server name being in the path, when the server is already provided in the -ServerInstance parameter. So, how can I change the path from \\$target_server\T$\PowerShell\backups to T:\Powershell\backups ?
I need to make this change so it works for any server that is used as a parameter.