-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindows_script.ps1
More file actions
38 lines (34 loc) · 1.07 KB
/
windows_script.ps1
File metadata and controls
38 lines (34 loc) · 1.07 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
# windows_script.ps1
param (
[string]$Server = "localhost",
[string]$Database = "master",
[string]$Query
)
function Invoke-SqlQuery {
param($server, $database, $query)
$connectionString = "Server=$server;Database=$database;User Id=sa;Password=YourStrongPassword123!"
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
$command = $connection.CreateCommand()
$command.CommandText = $query
try {
$connection.Open()
$result = $command.ExecuteReader()
$table = @()
while ($result.Read()) {
$row = @{
ServerName = $result[0]
DatabaseName = $result[1]
Version = $result[2]
}
$table += $row
}
return $table
}
finally {
$connection.Close()
}
}
# Query SQL Server from PowerShell
$query = "SELECT @@SERVERNAME as ServerName, DB_NAME() as DatabaseName, @@VERSION as Version"
$result = Invoke-SqlQuery -Server $Server -Database $Database -Query $query
$result | Format-Table