LocalDb和SMO-如何选择将数据库文件放在何处? [英] LocalDb and SMO - how to choose where to put database files?

查看:184
本文介绍了LocalDb和SMO-如何选择将数据库文件放在何处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始尝试使用SQL Server 2012功能LocalDb.我正在针对我创建的实例(例如创建数据库)使用SMO进行一些powershell脚本编写.为此,我具有以下功能:

I've started to experiment with the SQL Server 2012 feature LocalDb. I'm doing some powershell scripting with SMO against the instances I create, such as creating databases. To do this, I have this function:

Function New-Database {
    Param(
        $server,
        $databaseName
    )
    $serverHandle = New-Object Microsoft.SqlServer.Management.Smo.Server($server)
    if($serverHandle.Databases.Name.Contains($databaseName)) {
        throw "Database $databaseName already exists"
    }

    $databaseHandle = New-Object Microsoft.SqlServer.Management.Smo.Database($serverHandle, $databaseName)
    $databaseHandle.Create()
}

使用LocalDb时,在C:\Users\<username>\中创建mdf和ldf文件.我想重写它,但是我找不到方法. $databaseHandle对象具有属性PrimaryFilePath,但这是只读的.看起来应该做起来很简单,但我只是不知道如何...

When using LocalDb, the mdf and ldf files are created in C:\Users\<username>\. I want to override this, but I'm failing to find out how. The $databaseHandle object has a property PrimaryFilePath, but that is read-only. It seems like something that should be dead-simple to do, but I just can't find out how...

解决方案 在以下答案的引导下,这是我需要的Powershell调用:

Solution Led by the answer below, here is the Powershell calls I needed:

    $fileGroup = New-Object Microsoft.SqlServer.Management.Smo.FileGroup($databaseHandle, "PRIMARY")
    $dataFile = New-Object Microsoft.SqlServer.Management.Smo.DataFile($fileGroup, "DataFile", $filePath)
    $fileGroup.Files.Add($dataFile)
    $databaseHandle.FileGroups.Add($fileGroup)

推荐答案

我认为

I think this thread from the SMO Forum contains the answer. You just need to translate it to SQL PowerShell syntax (which I believe is just a wrapper to SMO at this point).

这是VBScript代码段:

Here's the VBScript snippet:

databaseHandle.FileGroups.Add(New FileGroup(db, "PRIMARY"))
databaseHandle.FileGroups(0).Files.Add(
    New DataFile(db.FileGroups(0), "TestName", "D:\SqlBancos\Teste\Teste1.mdf"))

这篇关于LocalDb和SMO-如何选择将数据库文件放在何处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆