• PowerShell查询sql server


    function Invoke-SQL1:

    function Invoke-SQL {
        param(
            [string] $DBServer,
            [string] $Database,
            [string] $SQLCMD
          )
    
        $connectionString = "Data Source=$DBServer; " + "Integrated Security=SSPI; " + "Initial Catalog=$Database"
        $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
        $command = new-object system.data.sqlclient.sqlcommand($SQLCMD,$connection)
        $connection.Open()
    
        $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
        $dataset = New-Object System.Data.DataSet
        $adapter.Fill($dataSet) | Out-Null
    
        $connection.Close()
        $dataSet.Tables
    
    }
    $DBServer = "scvmm"
    $Database = "appcontroller"
    $SQLCMD = "select * from [authz].[UserRoleMembers]"
    
    
    Invoke-SQL $Server $Database $SQLCMD

    function SQL2:

    function sql($sqlText, $database = "master", $server = ".")
    {
        $connection = new-object System.Data.SqlClient.SQLConnection("Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database");
        $cmd = new-object System.Data.SqlClient.SqlCommand($sqlText, $connection);
    
        $connection.Open();
        $reader = $cmd.ExecuteReader()
    
        $results = @()
        while ($reader.Read())
        {
            $row = @{}
            for ($i = 0; $i -lt $reader.FieldCount; $i++)
            {
                $row[$reader.GetName($i)] = $reader.GetValue($i)
            }
            $results += new-object psobject -property $row            
        }
        $connection.Close();
    
        $results
    }

    SQL Query3:

    $ServerName = "_ServerName_"
    $DatabaseName = "_DatabaseName_"
    $Query = "SELECT * FROM Table WHERE Column = ''"
    
    #Timeout parameters
    $QueryTimeout = 120
    $ConnectionTimeout = 30
    
    #Action of connecting to the Database and executing the query and returning results if there were any.
    $conn=New-Object System.Data.SqlClient.SQLConnection
    $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerName,$DatabaseName,$ConnectionTimeout
    $conn.ConnectionString=$ConnectionString
    $conn.Open()
    $cmd=New-Object system.Data.SqlClient.SqlCommand($Query,$conn)
    $cmd.CommandTimeout=$QueryTimeout
    $ds=New-Object system.Data.DataSet
    $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
    [void]$da.fill($ds)
    $conn.Close()
    $ds.Tables

    from:http://stackoverflow.com/questions/8423541/how-do-you-run-a-sql-server-query-from-powershell

  • 相关阅读:
    获取打印页号列表
    数据库设计技巧系列(三)——选择键和索引
    SQL Server2000孤立用户解决方案
    在WinForm程序中嵌入ASP.NET[转]
    再谈如何遍历Asp.net窗体下所有的控件
    数据库设计技巧系列(二)——设计表和字段
    今天下午真郁闷……
    如何实现在Asp.net下XP风格的下拉菜单
    利用SQL语句得到客户端的IP地址
    国庆节快乐……
  • 原文地址:https://www.cnblogs.com/dreamer-fish/p/3941169.html
Copyright © 2020-2023  润新知