Powershell在连接字符串中使用命名实例失败

时间:2015-07-23 06:10:19

标签: shell powershell instance named

function Get-Type {
    param($type)  
    $types = @( 'System.Boolean', 'System.Byte[]', 'System.Byte', 'System.Char', 'System.Datetime', 'System.Decimal',
    'System.Double', 'System.Guid', 'System.Int16', 'System.Int32',
    'System.Int64', 'System.Single', 'System.UInt16', 'System.UInt32',
    'System.UInt64')
    if ( $types -contains $type ) 
    {
        Write-Output "$type"
    }
    else 
    {
        Write-Output 'System.String'
    } 
}

function Out-DataTable {
    [CmdletBinding()]
    param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)
    Begin
    {
        $dt = new-object Data.datatable  
        $First = $true 
    }
    Process
    {
        foreach ($object in $InputObject)
        {
            $DR = $DT.NewRow()  
            foreach($property in $object.PsObject.get_properties())
            {  
                if ($first)
                {  
                    $Col =  new-object Data.DataColumn  
                    $Col.ColumnName = $property.Name.ToString()  
                    if ($property.value)
                    {
                        if ($property.value -isnot [System.DBNull]) 
                        {
                            $Col.DataType = [System.Type]::GetType("$(Get-Type $property.TypeNameOfValue)")
                        }
                    }
                    $DT.Columns.Add($Col)
                }  
                if ($property.IsArray) 
                {
                    $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1
                }  
                else 
                {
                    $DR.Item($property.Name) = $property.value
                }
            }  
            $DT.Rows.Add($DR)  
            $First = $false
        }
    } 
    End
    { 
        Write-Output @(,($dt))
    }   
}  

try 
{
    add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0,
    Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch
    {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"}   try
    {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0,
    Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}  catch
    {add-type -AssemblyName "Microsoft.SqlServer.Smo"
} 


function Get-SqlType  
{ 
    param([string]$TypeName) 
    switch ($TypeName)  
    { 
        'Boolean' {[Data.SqlDbType]::Bit} 
        'Byte[]' {[Data.SqlDbType]::VarBinary} 
        'Byte'  {[Data.SQLDbType]::VarBinary} 
        'Datetime'  {[Data.SQLDbType]::DateTime} 
        'Decimal' {[Data.SqlDbType]::Decimal} 
        'Double' {[Data.SqlDbType]::Float} 
        'Guid' {[Data.SqlDbType]::UniqueIdentifier} 
        'Int16'  {[Data.SQLDbType]::SmallInt} 
        'Int32'  {[Data.SQLDbType]::Int} 
        'Int64' {[Data.SqlDbType]::BigInt} 
        'UInt16'  {[Data.SQLDbType]::SmallInt} 
        'UInt32'  {[Data.SQLDbType]::Int} 
        'UInt64' {[Data.SqlDbType]::BigInt} 
        'Single' {[Data.SqlDbType]::Decimal}
        default {[Data.SqlDbType]::VarChar} 
    } 
}

function Add-SqlTable  
{
    [CmdletBinding()] 
    param( 
        [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, 
        [Parameter(Position=1, Mandatory=$true)] [string]$Database, 
        [Parameter(Position=2, Mandatory=$true)] [String]$TableName, 
        [Parameter(Position=3, Mandatory=$true)] [System.Data.DataTable]$DataTable, 
        [Parameter(Position=4, Mandatory=$false)] [string]$Username, 
        [Parameter(Position=5, Mandatory=$false)] [string]$Password, 
        [ValidateRange(0,8000)] 
        [Parameter(Position=6, Mandatory=$false)] [Int32]$MaxLength=1000,
        [Parameter(Position=7, Mandatory=$false)] [switch]$AsScript
    )

    try 
    {
        if($Username) 
        { 
            $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance,$Username,$Password 
        } 
        else 
        { 
            $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance 
        } 
        $con.Connect() 
        $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con 
        $db = $server.Databases[$Database] 
        $table = new-object ("Microsoft.SqlServer.Management.Smo.Table") $db, $TableName 
        foreach ($column in $DataTable.Columns) 
        {
            $sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)" 
            if ($sqlDbType -eq 'VarBinary' -or $sqlDbType -eq 'VarChar') 
            { 
                if ($MaxLength -gt 0) 
                {
                    $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType, $MaxLength
                }
                else
                { 
                    $sqlDbType  = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)Max"
                    $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType
                }
            }
            else 
            { 
                $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType 
            } 
            $col = new-object ("Microsoft.SqlServer.Management.Smo.Column") $table, $column.ColumnName, $dataType 
            $col.Nullable = $column.AllowDBNull 
            $table.Columns.Add($col) 
        } 
        if ($AsScript) {
            $table.Script()
        } 
        else 
        {
            $table.Create()
        }
    } 
    catch 
    {
        $message = $_.Exception.GetBaseException().Message
        Write-Error $message 
    }   
}   

function Write-DataTable 
{
    [CmdletBinding()]
    param(
        [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
        [Parameter(Position=1, Mandatory=$true)] [string]$Database,
        [Parameter(Position=2, Mandatory=$true)] [string]$TableName,
        [Parameter(Position=3, Mandatory=$true)] $Data,
        [Parameter(Position=4, Mandatory=$false)] [string]$Username,
        [Parameter(Position=5, Mandatory=$false)] [string]$Password,
        [Parameter(Position=6, Mandatory=$false)] [Int32]$BatchSize=50000,
        [Parameter(Position=7, Mandatory=$false)] [Int32]$QueryTimeout=0,
        [Parameter(Position=8, Mandatory=$false)] [Int32]$ConnectionTimeout=15
    )    
    $conn=new-object System.Data.SqlClient.SQLConnection($Username)
    { 
        $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout 
    }
    else
    { 
        $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout 
    }  
    $conn.ConnectionString=$ConnectionString
    try
    {
        $conn.Open()
        $bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString
        $bulkCopy.DestinationTableName = $tableName
        $bulkCopy.BatchSize = $BatchSize
        $bulkCopy.BulkCopyTimeout = $QueryTimeOut
        $bulkCopy.WriteToServer($Data)
        $conn.Close()
    }
    catch
    {
        $ex = $_.Exception
        Write-Error "$ex.Message"
        continue
    }   
}

$xmlfile = [xml](get-content "C:\SQLConfiguration.XML") set-location $xmlfile.configuration.folders.APP.Path  
$servername=$xmlfile.configuration.server.servername
foreach ($svr in get-content C:\justservers.txt) {
    $dt = new-object "System.Data.DataTable"
    $cn = new-object System.Data.SqlClient.SqlConnection "server=$svr;database=master;Integrated Security=sspi"
    $cn.Open()
    $sql = $cn.CreateCommand()
    $sql.CommandText = "select * from blah"

上面的代码适用于默认实例,但不适用于命名实例。

Justserver.txt文件包含默认和命名实例,如下所示 xxxxx xxxx \ ins01 xxx \ ins02

我在xxxx \ ins01上遇到错误,因为"异常调用带有0个参数的执行读取器"字符串或二进制数据将被截断"

感谢任何帮助

的问候,

2 个答案:

答案 0 :(得分:0)

实例名称之前的反斜杠是否被视为转义字符?尝试在代码中使用替换来逃避转义,如下所示:

$svr = $svr -replace '\\', '\\'
$cn = new-object System.Data.SqlClient.SqlConnection "server=$svr;database=master;Integrated Security=sspi"
    $cn.Open()

答案 1 :(得分:0)

Powershell没有问题,但我发现填充的数据中有一个coloumn长度不正常。我现在修好了,得到了预期的结果。谢谢大家,度过了愉快的周末