Powershell restore SQL Server database to new database

You don't have to use SMO just because your're in PowerShell.

import-module sqlps

$database = "NewDb"
$backupLocation = "D:\Backups\CurrentDB.bak"
$dataFileLocation = "D:\Databases\NewDB.mdf"
$logFileLocation = "D:\Logs\NewDB_log.ldf"

$sql = @"

USE [master]

ALTER DATABASE [$database] 
    SET SINGLE_USER WITH ROLLBACK IMMEDIATE

RESTORE DATABASE [$database] 
FROM DISK = N'$backupLocation' 
WITH FILE = 1,  
     MOVE N'CurrentDB' TO N'$dataFileLocation',  
     MOVE N'CurrentDB_log' TO N'$logFileLocation',  
     NOUNLOAD, REPLACE, STATS = 5

ALTER DATABASE [$database] 
    SET MULTI_USER
"@

invoke-sqlcmd $sql

And if you don't have sqlps installed, you can use System.Data.SqlClient from Powershell to run TSQL.


$RelocateData = [Microsoft.SqlServer.Management.Smo.RelocateFile]::new($CurrentDB, $NewDBmdf)
$RelocateLog = [Microsoft.SqlServer.Management.Smo.RelocateFile]::new($CurrentDBlog, $NewDBldf)

Restore-SqlDatabase -ServerInstance $SQLServer -Database $NewDB -BackupFile $backupfile `
-ReplaceDatabase -NoRecovery -RelocateFile @($RelocateData, $RelocateLog)