PowerShell 连接SQL

时间:2024-12-07 16:34:50

因为对SQL操作比较多,但有些操作其实都是重复性的,只是参数不太一样了,例如silo id, server name 等。希望可以通过powershell脚本提高效率。

尝试如下

1. 使用PowerShell 连接数据库,本地尝试,来至:http://www.pstips.net/getting-sql-server-connection-string.html.

当你用Powershell获取SQL连接字符串,你会需要“连接字符串”,这段字符串要包涵连接数据库实例的多个片段。

传统方法构建一个这样的字符串也不容易,下面有段函数也许可以帮助您完成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#requires -Version 2
function Get-ConnectionString
{
    $Path Join-Path -Path $env:TEMP -ChildPath 'dummy.udl'
   
    $null New-Item -Path $Path -ItemType File -Force
   
    $CommandArg """$env:CommonProgramFiles\System\OLE DB\oledb32.dll"",OpenDSLFile "  $Path
    Start-Process -FilePath Rundll32.exe -ArgumentList $CommandArg -Wait
    $ConnectionString Get-Content -Path $Path Select-Object -Last 1
    $ConnectionString | clip.exe
    Write-Warning -Message 'Connection String is also available from clipboard'
    $ConnectionString
}

当你运行Get-ConnectionString,Powershell会弹出一个对话框,你可以提交一个测试连接,接着关闭窗口,Powershell将返回一个一个连接字符串。

使用如下配置连接成功。

PowerShell 连接SQL

2. Powershell 连接SQL数据库,来至:http://www.pstips.net/accessing-an-sql-database-with-a-connection-string.html

先前的技巧中我们学习了如何创建一个SQL连接字符串,当你有了一个连接字符串并且它是有效的,接下来的例子就是演示如何向数据库提交一个SQL命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#requires -Version 2
# make sure this is a valid connection string to your database
# see www.connectionstrings.com for reference
$connectionString 'Provider=SQLOLEDB.1;Password=.topSecret!;Persist Security
 Info=True;User ID=sa;Initial Catalog=test;Data Source=myDBServer\SQLEXPRESS2012'
# make sure this is valid SQL for your database
# so in this case, make sure there is a table called "test"
$sql 'select * from test'
$db New-Object -ComObject ADODB.Connection
$db.Open($connectionString)
$rs $db.Execute($sql)
$results While ($rs.EOF -eq $false)
{
    $CustomObject New-Object -TypeName PSObject
    $rs.Fields | ForEach-Object -Process {
        $CustomObject Add-Member -MemberType NoteProperty -Name $_.Name -Value $_.Value
    }
    $CustomObject
    $rs.MoveNext()
}
$results Out-GridView