Powershell invoke-sqlcmd仅适用于Azure VM上的专用管理员连接

时间:2017-05-19 14:24:01

标签: sql powershell azure

我正在尝试使用Powershell和Invoke-Sqlcmd cmdlet来执行一些基本的数据库任务,例如分离数据库,附加新数据库,为数据库添加登录用户等等。

我正在安排一个任务来运行具有类似参数的批处理文件来执行这些任务:

powershell.exe -ExecutionPolicy Bypass "C:\Tasks\DownloadDBFromFTP.ps1"^
 -sourcePath 'C:\FTPSource\'^
 -destinationPath 'C:\SQL\Attach\'^
 -destinationConnectionString 'Data Source=(local);Initial Catalog=Sth;Integrated Security=False;User ID=foo;Password=bar'^
 -zipFileName 'Sth_Primary.zip'
  

以下是DownloadDBFromFTP.ps1的片段:

<# Detaches a database using a SQL Server Connection String. The Initial Catalog will be Detached. #>
Function DetachDatabase($connectionString)
{
    $sqlConnection = New-Object system.data.sqlClient.SqlConnectionStringBuilder($connectionString)
    $databaseName = $sqlConnection.InitialCatalog

    <# Set Database to SINGLE_USER and Close all connectsion #>
    $singleUserQuery = @"USE [master] GO ALTER DATABASE $databaseName SET  SINGLE_USER WITH ROLLBACK IMMEDIATE"@

    Write-Host "Set Database $databaseName To Single User Mode"
    try 
    {
        Invoke-Sqlcmd $singleUserQuery -QueryTimeout 3600 -ServerInstance $sqlConnection.DataSource -Username $sqlConnection.UserID -Password $sqlConnection.Password
    }
    catch 
    {
        # $_ is set to the ErrorRecord of the exception
        if ($_.Exception.InnerException) 
        {
            Write-Host $_.Exception.InnerException.Message
        } 
        else 
        {
            Write-Host $_.Exception.Message
        }
    }

这些操作从我们的一个Azure VM执行,没有任何错误,但出于某种原因我无法确定不同的Azure VM是否会抛出错误,无论查询如何。这里我尝试了一个基本的“SELECT GETDATE()”,我得到一个溢出或除以0错误:

Invoke-Sqlcmd : Arithmetic operation resulted in an overflow.
At F:\PowershellDBTransfer\DownloadDBFromFTP.ps1:71 char:3
+         Invoke-Sqlcmd -Query ("SELECT GETDATE()") -QueryTimeout 3600  ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], OverflowException
    + FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

作为最后的努力,我们尝试使用Invoke-Sqlcmd的-DedicatedAdministratorConnection参数,它运行正常。我们的一个数据库开发人员强烈建议不要这样做,所以我试图弄清楚这个特定虚拟机的不同之处。

0 个答案:

没有答案