PowerShell 数据库操作辅助脚本

该脚本为通用数据库操作,如果加载其他ADO.NET驱动(MYSQL,ORACLE等) 则可运行相关数据库的操作

主脚本

using namespace System.Reflection
using namespace System.Data.Common
using namespace System.Data
function Get-DbConnection {
    param (
        [string]$providerFile,
        [string]$providerName = ("System.Data.SqlClient"),
        [string]$connectionString
    )
    try {
        if (-not [string]::IsNullOrWhiteSpace($ProviderFile)) {
            [Assembly]$assembly = [Assembly]::LoadFrom($ProviderFile)
            [type]$type = $assembly.GetExportedTypes() | Where-Object { [DbProviderFactory].IsAssignableFrom($_) } | Select-Object -First 1
            if (!$type) {
                return @{RC = -1; MSG = "not implement DbProviderFactory class"; DATA = $null }
            }
            [FieldInfo]$fieldInfo = $type.GetField("Instance", [BindingFlags]::Public -bor [BindingFlags]::Static)
            if (!$fieldInfo) {
                return @{RC = -1; MSG = "this class is not contain 'Instance' static field."; DATA = $null }
            }
            [DbProviderFactory]$Factory = $fieldInfo.GetValue($null)
        }
        else {
            [DbProviderFactory]$Factory = [DbProviderFactories]::GetFactory($providerName)  
        }        
        $con = $Factory.CreateConnection()
        $con.ConnectionString = $ConnectionString
        return @{RC = 0; MSG = "OK"; DATA = $con } 
    }
    catch {
        return @{RC = -1; MSG = "Get-Connection:$($_Exception.Message)"; DATA = $con }
    }
}

function Get-DbCommand {
    param (
        [System.Data.Common.DbConnection]$conenction,
        [string]$commandText,
        [System.Data.CommandType]$commandType = ([System.Data.CommandType]::Text),
        [psobject[]]$parameters = $null,
        [int]$commandTimeout = 30,
        [System.Data.Common.DbTransaction]$transaction = $null
    )

    $cmd = $Conenction.CreateCommand()
    $cmd.CommandText = $commandText
    $cmd.CommandTimeout = $commandTimeout
    $cmd.CommandType = $commandType
    if ($null -ne $parameters) {
        foreach ($item in $parameters) {
            $param = $cmd.CreateParameter()
            $param.ParameterName = $item.parameterName
            $param.Direction = $item.direction
            $param.IsNullable = $item.isNullable
            $param.Value = $item.value
            $param.Size = $item.size
            $param.Precision = $item.precision
            $param.Scale = $item.scale
            $param.DbType = $item.dbType
            [void]$cmd.Parameters.Add($param)
        }    
    }
    
    $cmd.Transaction = $transaction
    return $cmd
}

function Get-NewParameter {
    <#
    .SYNOPSIS
    创建SQL参数
    
    .DESCRIPTION
    Long description
    
    .PARAMETER parameterName
    参数名称
    
    .PARAMETER direction
    参数方向
    
    .PARAMETER value
    参数值
    
    .PARAMETER dbType
    参数类型
    
    .PARAMETER size
    参数大小
    
    .PARAMETER scale
    参数标量
    
    .PARAMETER precision
    参数精度
    
    .PARAMETER isNullable
    参数是否为空
    
    .EXAMPLE
    Get-NewParameter -parameterName "@p1" -direction Output -dbType DateTime
    
    .NOTES
    General notes
    #>
    param (
        [Parameter(Mandatory = $true)]
        [ValidateNotNull()]
        [string]$parameterName,
        [System.Data.ParameterDirection]$direction = ([System.Data.ParameterDirection]::Input),
        [System.Object]$value = $null,
        [System.Data.DbType]$dbType = ([System.Data.DbType]::Object),
        [int]$size = 50,
        [int]$scale = 0,
        [int]$precision = 0,
        [bool]$isNullable = $true
        
    )
    return New-Object psobject -Property ([Ordered]@{ parameterName = $parameterName; direction = $direction; value = $value; size = $size; `
                scale = $scale; precision = $precision; dbType = $dbType ; isNullable = $isNullable 
        })
}


function Get-ExecuteNonQuery {
    param (
        [System.Data.Common.DbConnection]$connection,
        [string]$commandText,
        [System.Data.CommandType]$CommandType = ([System.Data.CommandType]::Text),
        [psobject[]]$parameters = $null,
        [int]$commandTimeout = 30,
        [System.Data.Common.DbTransaction]$transaction = $null,
        [switch]$close
    ) 
    try {
        [System.Data.Common.DbCommand]$cmd = Get-DbCommand -conenction $Connection -commandText $commandText -commandType $commandType `
            -parameters $parameters -commandTimeout $commandTimeout -transaction $transaction
        if ($connection.State -ne [System.Data.ConnectionState]::Open) { $connection.Open() }
        $effect = $cmd.ExecuteNonQuery()
        return @{RC = 0; MSG = "OK"; DATA = $effect }
    }
    catch {
        return @{RC = -1; MSG = $_.Exception.Message; Data = $nu }
    }
    finally {
        foreach ($p in $parameters ) {
            if ($p.direction -in @([System.Data.ParameterDirection]::Output, [System.Data.ParameterDirection]::InputOutput)) {
                $p.Value = $cmd.Parameters[$p.ParameterName].Value
            }            
        }        
        if ($null -ne $connection -and $close) { $connection.Close() }
    }    
}


function Get-ExecuteScalar {
    param (
        [System.Data.Common.DbConnection]$connection,
        [string]$commandText,
        [System.Data.CommandType]$CommandType = ([System.Data.CommandType]::Text),
        [psobject[]]$parameters = $null,
        [int]$commandTimeout = 30,
        [System.Data.Common.DbTransaction]$transaction = $null,
        [switch]$close
    ) 
    try {
        [System.Data.Common.DbCommand]$cmd = Get-DbCommand -conenction $Connection -commandText $commandText -commandType $commandType `
            -parameters $parameters -commandTimeout $commandTimeout -transaction $transaction
        if ($connection.State -ne [System.Data.ConnectionState]::Open) { $connection.Open() }
        $obj = $cmd.ExecuteScalar()
        return @{RC = 0; MSG = "OK"; DATA = $obj }
    }
    catch {
        return @{RC = -1; MSG = $_.Exception.Message; Data = $null }
    }
    finally {
        foreach ($p in $parameters ) {
            if ($p.direction -in @([System.Data.ParameterDirection]::Output, [System.Data.ParameterDirection]::InputOutput)) {
                $p.value = $cmd.Parameters[$p.ParameterName].Value
            }            
        }     
        if ($null -ne $connection -and $close) { $connection.Close() }
    }    
}

function Get-ExecuteReader {
    param (
        [ValidateNotNull()]
        [Parameter(Mandatory = $true)]
        [System.Data.Common.DbConnection]$connection,
        [ValidateNotNull()]
        [Parameter(Mandatory = $true)]
        [string]$commandText,
        [System.Data.CommandType]$commandType = ([System.Data.CommandType]::Text),
        [psobject[]]$parameters = $null,
        [int]$commandTimeout = 30,
        [System.Data.Common.DbTransaction]$transaction = $null,
        [switch]$close
    )
    $resultList = [Ordered]@{}; $j = 0
    try {
        [System.Data.Common.DbCommand]$cmd = Get-DbCommand -conenction $Connection -commandText $commandText -commandType $commandType `
            -parameters $parameters -commandTimeout $commandTimeout -transaction $transaction
        if ($connection.State -ne [System.Data.ConnectionState]::Open) { $connection.Open() }
        $reader = $cmd.ExecuteReader()
        do {            
            $tempList = @()      
            while ($reader.Read()) {
                $property = [Ordered]@{}
                for ($i = 0; $i -lt $reader.FieldCount; $i++) { $property.($reader.GetName($i)) = $reader.GetValue($i) }
                $tempList += New-Object psobject -Property $property
            }
            $resultList.("Table$($j)") = $tempList; $j++           
        } while ($reader.NextResult())
   
        return @{RC = 0; MSG = "OK"; DATA = $resultList }
    }
    catch {
        return @{RC = -1; MSG = "Get-Reader:$($_.Exception.Message)"; DATA = $null }
    }
    finally {
        if ($null -ne $reader) {
            $reader.Close()
            foreach ($p in $parameters ) {
                if ($p.direction -in @([System.Data.ParameterDirection]::Output, [System.Data.ParameterDirection]::InputOutput)) {
                    $p.Value = $cmd.Parameters[$p.ParameterName].Value
                }                
            }    
        }
        if ($null -ne $Connection -and $close) { $Connection.Close() }        
    }    
}

function Get-Schema {
    param (
        [ValidateNotNull()]
        [Parameter(Mandatory = $true)]
        [System.Data.Common.DbConnection]$connection,
        [ValidateNotNull()]
        [Parameter(Mandatory = $true)]
        [string]$commandText,
        [System.Data.CommandType]$commandType = ([System.Data.CommandType]::Text),
        [psobject[]]$parameters = $null,
        [int]$commandTimeout = 30,
        [System.Data.Common.DbTransaction]$transaction = $null,
        [switch]$close
    )
    $resultList = [Ordered]@{}; $j = 0
    try {
        [System.Data.Common.DbCommand]$cmd = Get-DbCommand -conenction $Connection -commandText $commandText -commandType $commandType `
            -parameters $parameters -commandTimeout $commandTimeout -transaction $transaction
        if ($connection.State -ne [System.Data.ConnectionState]::Open) { $connection.Open() }
        $reader = $cmd.ExecuteReader([System.Data.CommandBehavior]::SchemaOnly)
        do {
            $table = $reader.GetSchemaTable()
            $tempList = @()      
            foreach ($row in $table.Rows) {
                $properties = [ordered]@{}
                for ($i = 0; $i -lt $table.Columns.Count; $i++) {
                    $properties.($table.Columns[$i]) = $row[$i]
                }
                $tempList += New-Object psobject -Property $properties
            }
            $resultList.("Schema$($j)") = $tempList; $j++           
        } while ($reader.NextResult())
   
        return @{RC = 0; MSG = "OK"; DATA = $resultList }
    }
    catch {
        return @{RC = -1; MSG = "Get-Reader:$($_.Exception.Message)"; DATA = $null }
    }
    finally {
        if ($null -ne $reader) {
            $reader.Close()
            foreach ($p in $parameters ) {
                if ($p.direction -in @([System.Data.ParameterDirection]::Output, [System.Data.ParameterDirection]::InputOutput)) {
                    $p.Value = $cmd.Parameters[$p.ParameterName].Value
                }                
            }    
        }
        if ($null -ne $Connection -and $close) { $Connection.Close() }        
    }    
}

客户端调用

using namespace System
Import-Module .\DbHelper.psm1 -Force

$con = Get-DbConnection -connectionString "Data Source=localhost;Initial Catalog=highwavedw;User id=sa;password=password"
$p1 = Get-NewParameter -parameterName "@p1" -direction Output -dbType DateTime
$p2 = Get-NewParameter -parameterName "@p2" -value "U" -dbType String
$reault = Get-ExecuteReader -connection $con.DATA -commandText "Select * from sys.objects Where Type=@p2;select * from sys.columns;select @p1=getdate()" -parameters @($p1, $p2)
$reault.DATA.Table1 | Format-Table

调用结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
中文名: PowerShell脚本编写手册 原名: Windows Powershell Scripting Guide 作者: Ed Wilson 资源格式: PDF 版本: 影印版 出版社: Microsoft Press书号: 073562279发行时间: 2008年 地区: 美国 语言: 英文 内容简介: Get practical guidance for using Windows PowerShell to manage Windows Vista and Windows Server 2008. Written by Ed Wilson, a leading scripting expert and trainer at Microsoft, this reference offers a task-based approach to help you find the information you need for day-to-day tasks. With more than 200 scripts, it offers rich examples that administrators can customize for their own environment and needs. The scripts range in complexity from one-line commands, to full-blown scripts with managed output and command-line arguments examples that are applicable to all skill levels. Includes a companion CD with fully searchable eBook, sample scripts, and other resources for managing your Windows-based environment.Key Book Benefits Delivers more than 200 scripts administrators can customize and use to get up and running quickly Provides multiple ways of accomplishing tasks: from one-line commands to full-blown scripts with managed output and command-line arguments Features a task-oriented approach, and organized to help you quickly find the information you need for your day-to-day activities Includes a companion CD with a fully searchable eBook, sample scripts, and other resources for on-the-job results 目录: 1. The Shell in Windows Powershell. 2. Scripting Windows Powsershell 3. Managing Logs 4. Managing Services 5. Managing Shares 6. Managing Printing 7. Desktop Maintenance 8. Networking 9. Configuration Desktop Settings 10. Managing Post-Deployment Issues 11. Managing User Data 12. Troubleshooting Windows 13. Managing Domain Users 14. Configuring the Cluster Service 15. Managing Internet Information Services 16. Working with the Certificate Store 17. Managing the Terminal Services Service 18. Configuring Network Services 19. Working with Windows Server 2008 Server Core

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值