forked from anwather/My-Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_Example.ps1
More file actions
96 lines (78 loc) · 2.67 KB
/
db_Example.ps1
File metadata and controls
96 lines (78 loc) · 2.67 KB
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
94
95
96
$serverList = "AUS-CM01", "AUS-SCSM01", "AUS-SCSM02", "AUS-SCOM01", "AUS-SCORCH01"
#$serverList = "AUS-SCORCH01","AUS-CM01"
$resultServer = "AUS-SCORCH01"
$resultDB = "PatchingAdmin"
$sb = {
Param($Params)
$serverName = $params.ServerName
$dbname = "msdb"
$query = @"
Select @@ServerName AS ServerName,@@Version As Version
"@
#Create the connection object
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=$servername; Database=$dbname; Integrated Security = True"
#Create the command object
$sqlcmd = New-Object System.Data.SqlClient.SqlCommand
$sqlcmd.CommandText = $query
$sqlcmd.Connection = $sqlConnection
Write-Output $sqlcmd.CommandText
#Retrieve data
$sqlConnection.Open()
$result = $sqlcmd.ExecuteReader()
#Store results in a data table object
$table = New-Object System.Data.DataTable
$table.Load($result)
#Close the connection
$SqlConnection.Close()
return $table
}
$updatesb = {
Param($Params)
$serverName = $params.ServerName
$version = $params.Version
$dbname = "PatchingAdmin"
$query = @"
INSERT INTO [dbo].[Versions]
([ServerName]
,[Version]
,[LastUpdated])
VALUES
(`'$serverName`'
,`'$version`'
,GETDATE())
"@
#Create the connection object
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=$using:resultServer; Database=$using:resultDB; Integrated Security = True"
#Create the command object
$sqlcmd = New-Object System.Data.SqlClient.SqlCommand
$sqlcmd.CommandText = $query
$sqlcmd.Connection = $sqlConnection
#Write the data
$sqlConnection.Open()
$sqlcmd.ExecuteNonQuery() | Out-Null
$sqlConnection.Close()
}
foreach ($server in $serverList) {
if (Test-Connection -ComputerName $server -Count 1 -Quiet) {
$params = @{
ServerName = $server
}
$session = New-PSSession -ComputerName $server
$result = Invoke-Command -Session $session -ArgumentList $params -ScriptBlock $sb
Remove-PSSession $session
#Transform the results
$params = @{
ServerName = $result.ServerName
Version = $result.Version.Split() | Select-String -Pattern "^\d{2}`.\d{1}`.\d{4}`.\d{1}$"
}
#Write to the db
$session = New-PSSession -ComputerName $resultServer
$result = Invoke-Command -Session $session -ArgumentList $params -ScriptBlock $updatesb
Remove-PSSession $session
}
else {
Write-Output "Server $server is not responding"
}
}