-
Notifications
You must be signed in to change notification settings - Fork 63
/
Script-DBObjectsSMO.ps1
93 lines (80 loc) · 2.29 KB
/
Script-DBObjectsSMO.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# Script server objects
#
# Requires Windows Powershell to be installed
# (http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx)
#
# Returns zero for success, non-zero for failure
#
# RNM 10.10.2007
#------------------
#trap {
# "AN ERROR OCCURRED! :-("
# return 255
# }
[reflection.assembly]::LoadwithPartialName("Microsoft.SQLServer.SMO") | out-Null
# Set variables
[boolean]$defaulted = $false
if ($args[0] -ne $null) {
$server = $args[0] }
else {
$server = "default_server"
$defaulted = $true
}
if ($args[1] -ne $null) {
$filename = $args[1] }
else {
$filename = "E:\Dexma\logs\" + $server + "_ScriptedObjects.txt"
$defaulted = $true
}
if ($args[2] -ne $null) {
$action = $args[2] }
else {
$action = "linkedservers"
$defaulted = $true
}
# Delete output file if it exists already
#if ($filename -ne $null){
# remove-Item $filename
# }
# Create SQL Server object
$sql = New-Object 'Microsoft.sqlserver.management.smo.server' $server
# Create SQL Server ScriptingOptions object
$scropt = New-Object 'Microsoft.sqlserver.management.smo.scriptingoptions'
$scropt.FileName = $filename
$scropt.includeheaders = $true
$scropt.appendtofile = $true
# Script required objects
switch ($action) {
"linkedservers" {
# Script linked servers
$sql.LinkedServers | foreach-Object {$_.script($scropt) | out-null}
}
"logins" {
# Script logins
$sql.Logins| foreach-Object {$_.script($scropt) | out-null}
}
"jobs" {
# Script logins
$sql.JobServer.jobs| foreach-Object {$_.script($scropt) | out-null}
}
default {
# Exit with failure code
"ERROR: Action not recognised"
return 2
}
}
# Print results
$action + " on " + $server + " scripted to " + $filename
# If we defaulted any of the values then issue a warning, otherwise exit cleanly
if ($defaulted -eq $false) {
return
}
else
{
""
"WARNING: One or more of the required command line parameters was not provided. Defaults were used"
""
"Expected parameters: "
" <server> <filename to script to> <linkedservers|logins>"
return 1
}