我想以MDF和LDF文件保留在脚本执行文件夹中的方式创建LocalDB数据库。
我知道我们可以轻松地在PowerShell中使用$
运算符进行命令替换,因此,如果我声明$pwd
之类的内容,它将替换为pwd
的输出}命令。
从here开始,我知道Invoke-SqlCmd
不是使用LocalDB实例做事的简单方法。
我想通过PowerShell执行以下命令。我怎么能做到这一点?
sqlcmd -S "(localdb)\MSSQLLocalDB" -Q "
CREATE DATABASE [Test] ON PRIMARY (
NAME = N'Test',
FILENAME = N'<$pwd output here>\Test.mdf'
)
LOG ON (
NAME = N'Test_log',
FILENAME = N'<$pwd output here>\Test_log.ldf'
)"
答案 0 :(得分:1)
这可能比您要求的要多得多,但它会解决您的问题。
这将询问您是否要从模板还原,否则它将创建一个空数据库。
$backupFilePath=''
$TempDB=''
$TempDBlog=''
$DBName=''
$Logfilepath=''
$Datafilepath=''
$confirmation = Read-Host "Do you want to use a DB template? [y/n]"
If($confirmation.ToUpper().StartsWith("Y") )
{
$dbCommand = "use [master];RESTORE DATABASE [$DBName] " + "FROM DISK = N'$backupFilePath'" + "WITH FILE = 1, NOUNLOAD, STATS = 10, " + "move '$TempDB' to '$Datafilepath" + "\" + "$DBName" + ".mdf', " + "move '$TempDBlog' to '$Logfilepath" + "\" + "$DBName" + ".ldf';" + "alter database [$DBName] modify file (name=N'$TempDB ', newname=N'$DBName" + "_data1');" + "alter database [$DBName] modify file (name=N'$TempDBlog', newname=N'$DBName" + "_log1');" + "alter database [$DBName] set read_committed_snapshot on with rollback immediate;" + "alter database [$DBName] set COMPATIBILITY_LEVEL = 100;"
}
else {
$dbCommand = "use [master];CREATE DATABASE [$DBName] ON " + "( NAME='$DBName" + "_data1', FILENAME='$Datafilepath" + "\" + "$DBName" + "_data1.mdf', SIZE=1GB, MAXSIZE=UNLIMITED, FILEGROWTH=200MB)" + "LOG ON ( NAME='$DBName" + "_log1', FILENAME='$Logfilepath" + "\" + "$DBName" + "_log1.ldf', SIZE=1GB, MAXSIZE=UNLIMITED, FILEGROWTH=200MB); " + "alter database [$DBName] set read_committed_snapshot on with rollback immediate;" + "alter database [$DBName] set COMPATIBILITY_LEVEL = 100; " + "set AUTO_CLOSE OFF;"
}
有人必须将其编辑为漂亮的代码中断,因为它不允许我这样做。