-->

调用新对象时,构造上微软DacServices Powershell的错误(Microsoft Da

2019-10-20 07:32发布

我有我试图运行下面的PowerShell脚本:

add-type -path "C:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin\Microsoft.SqlServer.Dac.dll";
$d = new-object Microsoft.SqlServer.Dac.DacServices "server=localhost"

# Load dacpac from file & deploy to database named pubsnew 
$dp = [microsoft.sqlserver.dac.dacpackage]::load("c:\deploy\MyDbDacPac.dacpac") 
$d.deploy($dp, "MyDb", $true)

然而,在运行时,我收到以下错误:

New-Object : Exception calling ".ctor" with "1" argument(s): "The type initializer for 'Microsoft.SqlServer.Dac.DacServices' threw an exception."
At C:\Scripts\DeployDacPac.ps1:3 char:16
+ $d = new-object <<<<  Microsoft.SqlServer.Dac.DacServices "server=localhost"
+ CategoryInfo          : InvalidOperation: (:) [New-Object],                      MethodInvocationException
+ FullyQualifiedErrorId : Cons  tructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

我想对于一个自动化的数据库部署运行这一点,但不能让过去这个奇怪的错误。 我已经把我的执行策略为RemoteSigned并更新了对PowerShell运行时版本的.NET 4.0。 想不出还有什么可能是错误的。

任何帮助将不胜感激!

Answer 1:

这里的问题是,默认的验证方法是需要一个用户名和密码的SQL Server身份验证。 你要么需要提供这些参数或明确指定Windows身份验证应该使用。 您可以通过以下替换您的连接字符串参数做到这一点。

"server=localhost;Integrated Security = True;"

另外,您也可以使用下面的函数来封装此逻辑。 请注意,默认参数设置为“WindowsAuthentication”,这不包括用户名或密码参数。 如果你提供任一,PowerShell的将使用“SqlServerAuthentication”参数设置和$ PSCmdlet.ParameterSetName变量将被适当地设定。

function Get-DacServices()
{
    [CmdletBinding(DefaultParameterSetName="WindowsAuthentication")]
    Param(
        [string]$ServerName = 'localhost',
        [Parameter(ParameterSetName='SqlServerAuthentication')]
        [string]$UserName,
        [Parameter(ParameterSetName='SqlServerAuthentication')]
        [string]$Password
    )

    $connectionString = "server=$serverName;";

    if($PSCmdlet.ParameterSetName -eq 'SqlServerAuthentication')
    {
        $connectionString += "User ID=$databaseUsername;Password=$databasePassword;";
    }
    else
    {
        $connectionString += "Integrated Security = True;";
    }

    $result = new-object Microsoft.SqlServer.Dac.DacServices $connectionString;

    return $result;
}


文章来源: Microsoft DacServices Powershell error on constructor when calling new-object