我正在尝试通过PowerShell将bak文件恢复到我的SQL Server实例。
在将它放入脚本之前,我试图从PowerShell提示符
执行命令 cmd.exe /C SqlCmd -E -S COMPUTER01 -Q "RESTORE DATABASE TestDB FROM DISK = N'.\TestDB.bak' WITH FILE = 1, MOVE N'TESTING' TO N'.\DataStore\TestDB.mdf', MOVE N'TESTING_log' TO N'.\LogStore\TestDB.ldf', NOUNLOAD, STATS = 5"
它引发了错误
关键字'附近有'的语法不正确。如果此语句是公用表表达式,xmlnamespaces子句或更改跟踪上下文子句,则必须以分号结束前一个语句。
然后我更改了我的cmd以添加分号
cmd.exe /C SqlCmd -E -S COMPUTER01 -Q "RESTORE DATABASE TestDB FROM DISK = N'.\TestDB.bak'**;** WITH FILE = 1, MOVE N'TESTING' TO N'.\DataStore\TestDB.mdf', MOVE N'TESTING_log' TO N'.\LogStore\TestDB.ldf', NOUNLOAD, STATS = 5"
现在,它正在抛出错误:
"语法不正确..."
有人可以给我一份工作代码,我可以
我在PowerShell 5中使用脚本,而不需要仅使用cmd.exe /C SqlCmd
。如果有更好的方法,那么我也会适应它。
答案 0 :(得分:1)
这可以做你想要的,但它不会问你数据库是否存在。这需要更多的代码行,这真的很重要,因为你将删除数据库\无论如何重写它。
$DBName="TestDB"
$backupFilePath="D:\TESTDB.bak"
$Datafilepath="D:\DataStore" #Do not add the trailing \
$Logfilepath="D:\LogStore" #Do not add the trailing \
$dbCommand = "use [master];RESTORE DATABASE [$DBName] " + "FROM DISK = N'$backupFilePath'" + "WITH FILE = 1, NOUNLOAD, STATS = 10, " + "move 'TESTING' to '$Datafilepath" + "\" + "$DBName" + "_data1.mdf', " + "move 'TESTING_log' to '$Logfilepath" + "\" + "$DBName" + "_log1.ldf';" + "alter database [$DBName] modify file (name=N'TESTING', newname=N'$DBName" + "_data1');" + "alter database [$DBName] modify file (name=N'TESTING_log', newname=N'$DBName" + "_log1');" + "alter database [$DBName] set read_committed_snapshot on with rollback immediate;" + "alter database [$DBName] set COMPATIBILITY_LEVEL = 100;"
sqlcmd -S $DBServerName -E -Q $dbCommand -r0