从函数调用函数时,从PowerShell连接到SQL Server数据库

时间:2016-10-03 07:32:27

标签: sql-server powershell

我正在使用PowerShell脚本。我有一些高级

  1. 从.txt文件中过滤$server$instance名称。
  2. 使用$server$instance进入2函数连接到SQL Server
  3. 我的.txt文件代码如下

    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
    
    # Get our list of target servers from the local servers.txt file(Need
    $servers = Get-Content 'mirroringserver.txt'
    
    foreach ($prcs in $servers) {
        # The first entry in the file is the machine name, the second is the instance name so separate them
        #$srvc = $prcs.Split($prcs, "\r\n")
        # $ServerName = $prcs
        $srvc = $prcs.Split('\')
    
        $servers  = $srvc[0]
        $instance = $srvc[1]
        GetConnectionString $servers $instance
        # Ping the machine to see if it's on the network
        $results = gwmi -query "select StatusCode from Win32_PingStatus where Address = '$servers'"
    
        $responds = $false
        foreach ($result in $results) {
            # If the machine responds break out of the result loop and indicate success
            if ($result.StatusCode -eq 0) {
                $responds = $true
                break
            }
        }
    
        if ($responds) {
            # Check to see if a directory exists for this machine, if not create one
            if (!(Test-Path -Path .\$servers)) {
                New-Item .\$servers\ -Type Directory
            }
    
            # Get the server info in the first function and the instance info in the second
    
            #mirroring $servers $instance
            getInsertServerStatus $servers $instance
        } else {
            # Let the user know we couldn't connect to the server
            Write-Output "$servers does not respond"
        }
    }
    
    function GetConnectionString([string]$svr, [string]$inst) {
        return "Server=$svr\$inst;Database=master;Integrated Security=True;"
    }
    

    这是我的功能1:

    function mirroring(
        $svr,
        $inst,
        [string] $datastore,
        [string] $datastore1,
        [string] $datastore2,
        [string] $datastore3,
        [string] $datastore4,
        [string] $datastore5,
        [string] $datastore6,
        [string] $datastore7
    ) {
        $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
        $SqlConnection.ConnectionString = GetConnectionString
        $SqlConnection.Open()
        $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
        $SqlCmd.CommandText = " SELECT  db_name(sd.[database_id])AS [Database Name]
                ,sd.mirroring_state                  AS [Mirror State Number]
                ,sd.mirroring_state_desc             AS [Mirror State]
                ,sd.mirroring_partner_name           AS [Partner Name]
                ,sd.mirroring_role_desc              AS [Mirror Role]
                ,sd.mirroring_safety_level_desc      AS [Safety Level]
                ,sd.mirroring_witness_name           AS [Witness]
                ,sd.mirroring_connection_timeout AS [Timeout(sec)]
            FROM sys.database_mirroring AS sd
            WHERE mirroring_guid IS NOT null
            ORDER BY [Database Name];"
        $SqlCmd.Connection = $SqlConnection
        $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
        $SqlAdapter.SelectCommand = $SqlCmd
        $DataSet = New-Object System.Data.DataSet
        $SqlAdapter.Fill($DataSet)
        $DataSet.Tables[0]
        $SqlConnection.Close()
        $datastore = $DataSet.Tables[0].Rows[0][0]
        $datastore1 = $DataSet.Tables[0].Rows[0][1]
        $datastore2 = $DataSet.Tables[0].Rows[0][2]
        $datastore3 = $DataSet.Tables[0].Rows[0][3]
        $datastore4 = $DataSet.Tables[0].Rows[0][4]
        $datastore5 = $DataSet.Tables[0].Rows[0][5]
        $datastore6 = $DataSet.Tables[0].Rows[0][6]
        $datastore7 = $DataSet.Tables[0].Rows[0][7]
        $script:ServerStatus1 = "DataBase Name:"+ $datastore+",Mirror State Number"+$datastore1+",Mirror State"+$datastore2+",Partner Name"+$datastore3+",Mirror Role"+$datastore4+",Safety Level"+$datastore5+",Witness"+$datastore6+",Timeout(In Sec)"+$datastore7
        return $script:ServerStatus1
    }
    

    这是我的功能2:

    function getInsertServerStatus(
        $svr1,
        $inst2,
        $ServerName = $svr1+"\"+$inst2,
        $RemActonToBeTaken = 0,
        $ServerStatus
    ) {
        mirroring
        $Script:ServerStatus1
        $Script:ServerStatus= $ServerStatus1
    
        Write-Host "ServerName=$ServerName"
        Write-Host "InstanceName=$inst2"
        Write-Host "ServerStatus=$ServerStatus1"
        Write-Host "RemActonToBeTaken=$RemActonToBeTaken"
    
        $SqlConnection1 = New-Object System.Data.SqlClient.SqlConnection
        $SqlConnection1.ConnectionString = "Server=$svr1\$inst2;Database=master;Integrated Security=True;"
        $SqlConnection1.Open()
        $SqlCmd1 = New-Object System.Data.SqlClient.SqlCommand
        $SqlCmd1.CommandText = "USP_RemedialActionDetails"
        $SqlCmd1.Connection = $SqlConnection1
        $SqlCmd1.CommandType = [System.Data.CommandType]::StoredProcedure
    
        $InParameter1 = New-Object System.Data.SqlClient.SqlParameter;
        $InParameter1 = $SqlCmd1.Parameters.Add("@ServerName" , [System.Data.SqlDbType]::String)
        $InParameter1.Value = $ServerName
        $InParameter1.Direction = [System.Data.ParameterDirection]"Input";
    
        $InParameter2 = New-Object System.Data.SqlClient.SqlParameter;
        $InParameter2=$SqlCmd1.Parameters.Add("@InstanceName" , [System.Data.SqlDbType]::String)
        $InParameter2.Value = $inst2
        $InParameter2.Direction = [System.Data.ParameterDirection]"Input";
    
        $InParameter3 = New-Object System.Data.SqlClient.SqlParameter;
        $InParameter3=$SqlCmd1.Parameters.Add("@ServerStatus" , [System.Data.SqlDbType]::String)
        $InParameter3.Value = $ServerStatus1
        $InParameter3.Direction = [System.Data.ParameterDirection]"Input";
    
        $InParameter4 = New-Object System.Data.SqlClient.SqlParameter;
        $InParameter4=$SqlCmd1.Parameters.Add("@RemActionToBeTaken" , [System.Data.SqlDbType]::String)
        $InParameter4.Value = $RemActonToBeTaken
        $InParameter4.Direction = [System.Data.ParameterDirection]"Input";
    
        $result = $SqlCmd1.ExecuteNonQuery()
        Write "result=$result"
        $SqlConnection1.Close()
        $SQLCmd1.Dispose() | Out-Null
    }
    

    我在函数mirroring内调用函数getInsertServerStatus。 连接字符串到函数(mirroring)连接错误,因为找不到$server$instance名称。

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些错误:

首先,在函数 getInsertServerStatusyou 内调用镜像而不传递参数$ svr $ inst ....     它应该是:

   mirroring  $svr1  $inst1  ... other parameters

second, Inside the function **mirroring** you call **GetConnectionString** 

没有传递参数$ servers $ instance     它应该是:

    GetConnectionString $svr  $inst

在主程序中,您调用GetConnectionString $ servers $ instance并且您没有将返回值传递给变量并且对您的代码没有影响,请删除此行

使用建议的代码修改代码。