-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction_copytable.ps1
43 lines (38 loc) · 1.38 KB
/
function_copytable.ps1
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Function CopyTable($srcServer, $srcDatabase, $destServer, $destDatabase, $bothTable)
{
$src = New-Object System.Data.SqlClient.SQLConnection
$dest = New-Object System.Data.SqlClient.SQLConnection
$src.ConnectionString = "SERVER=" + $srcServer + ";DATABASE=" + $srcDatabase + ";Integrated Security=True"
$dest.ConnectionString = "SERVER=" + $destServer + ";DATABASE=" + $destDatabase + ";Integrated Security=True"
$data = "SELECT * FROM " + $bothTable
$getData = New-Object System.Data.SqlClient.SqlCommand($data, $src)
try
{
$src.Open()
$dest.Open()
[System.Data.SqlClient.SqlDataReader] $reading = $getData.ExecuteReader()
try
{
$copy = New-Object Data.SqlClient.SqlBulkCopy($dest)
$copy.DestinationTableName = $bothTable
$copy.WriteToServer($reading)
Write-Host "Table copied from " + $srcServer + " to " + $destServer + "."
}
catch [System.Exception]
{
$ex = $_.Exception
throw($ex.Message)
}
finally
{
$reading.Close()
$src.Close()
$dest.Close()
}
}
catch
{
throw("Cannot open a connection to " + $destServer + ".")
}
}
CopyTable -srcServer "SERVONE\IN" -srcDatabase "DBOne" -destServer "SERVTWO\IN" -destDatabase "DBTwo" -bothTable "Table"