-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathCommon-Commands.sql
237 lines (183 loc) · 9.01 KB
/
Common-Commands.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
-- 1) Open SQL Server Management Studio and Connect to Server from PowerShell
ssms.exe <scriptfile> -S $serverName -E
-- 2) Add datetime in FileName
Write-Host "fileName_$(Get-Date -Format ddMMMyyyyTHHmm).sql";
-- 3) Unattended script execution
https://dba.stackexchange.com/questions/197360/how-to-execute-sql-server-query-in-ssms-using-powershell
sqlcmd -Q 'E:\PowerShell_PROD\Screenshot\ServerDetails.sql' -E -S localhost
-- 4) Get file name
"F:\Mssqldata\Data\UserTracking_data.mdf" -match "^(?'PathPhysicalName'.*[\\\/])(?'BasePhysicalName'.+)"
$Matches['BasePhysicalName'] => UserTracking_data.mdf
$Matches['PathPhysicalName'] => F:\Mssqldata\Data\
-- 5) Is Null or Empty
[string]::IsNullOrEmpty($StopAt_Time) -eq $false
-- 6) Create a PS Drive for Demo Purposes
New-PSDrive -Persist -Name "P" -PSProvider "FileSystem" -Root "\\Tul1cipedb3\g$"
-- 7) Add color to Foreground and Background text
write-host "[OK]" -ForegroundColor Cyan
-- 7) File exists or not
[System.IO.File]::Exists($n)
-- 8) Get all files on drive by Size
Get-ChildItem -Path 'F:\' -Recurse -Force -ErrorAction SilentlyContinue |
Select-Object Name, @{l='ParentPath';e={$_.DirectoryName}}, @{l='SizeBytes';e={$_.Length}}, @{l='Owner';e={((Get-ACL $_.FullName).Owner)}}, CreationTime, LastAccessTime, LastWriteTime, @{l='IsFolder';e={if($_.PSIsContainer) {1} else {0}}}, @{l='SizeMB';e={$_.Length/1mb}}, @{l='SizeGB';e={$_.Length/1gb}} |
Sort-Object -Property SizeBytes -Descending | Out-GridView
-- 9) Check if -Verbose switch is used
$PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent
-- 10) Check if Module is installed
if (Get-Module -ListAvailable -Name SqlServer) {
Write-Host "Module exists"
} else {
Write-Host "Module does not exist"
}
-- 11) Find path of SQLDBATools Module
(Get-Module -ListAvailable SQLDBATools).Path
-- 12) Log entry into ErrorLogs table
$MessageText = "Get-WmiObject : Access is denied. Failed in execution of Get-ServerInfo";
Write-Host $MessageText -ForegroundColor Red;
Add-CollectionError -ComputerName $ComputerName -Cmdlet 'Add-ServerInfo' -CommandText "Add-ServerInfo -ComputerName '$ComputerName'" -ErrorText $MessageText -Remark $null;
return;
-- 13) Querying using SQLProvider
$computerName = 'TUL1CIPEDB2'
Get-ChildItem SQLSERVER:\SQL\$computerName\DEFAULT
$sqlInstance = Get-Item SQLSERVER:\SQL\$computerName\DEFAULT
$sqlInstance | gm -MemberType Property
$sqlInstance | select ComputerNamePhysicalNetBIOS, Name, Edition, ErrorLogPath, IsCaseSensitive, IsClustered,
IsHadrEnabled, IsFullTextInstalled, LoginMode, NetName, PhysicalMemory,
Processors, ServiceInstanceId, ServiceName, ServiceStartMode,
VersionString, Version, DatabaseEngineEdition
$sqlInstance.Information | Select-Object * | fl
$sqlInstance.Properties | Select-Object Name, Value | ft -AutoSize
$sqlInstance.Configuration
-- 14) Querying SqlServer using PowerShell
$computerName = 'TUL1CIPEDB2'
<# SMO #>
$server = New-Object Microsoft.SqlServer.Management.Smo.Server("$computerName")
$server | Select-Object ComputerNamePhysicalNetBIOS, Name, Edition, ErrorLogPath, IsCaseSensitive, IsClustered,
IsHadrEnabled, IsFullTextInstalled, LoginMode, NetName, PhysicalMemory,
Processors, ServiceInstanceId, ServiceName, ServiceStartMode,
VersionString, Version, DatabaseEngineEdition
$server.Configuration.MaxServerMemory
$server.Configuration.CostThresholdForParallelism
$server.Configuration.MinServerMemory
$server.Configuration.MaxDegreeOfParallelism
$server.Configuration.Properties | ft -AutoSize -Wrap
<# SQL Provider #>
Get-ChildItem SQLSERVER:\SQL\$computerName\DEFAULT
$sqlInstance = Get-Item SQLSERVER:\SQL\$computerName\DEFAULT
$sqlInstance.Databases['DBA'].Schemas
$sqlInstance.Databases['DBA'].Tables | Select-Object Schema, Name, RowCount
Get-ChildItem SQLSERVER:\SQL\$computerName\DEFAULT\Databases\DBA\Tables | Select-Object Schema, Name, RowCount;
(Get-Item SQLSERVER:\SQL\$computerName\DEFAULT\Databases\DBA\Tables).Collection | Select-Object Schema, Name, RowCount;
$sqlInstance | gm -MemberType Property
$sqlInstance | select ComputerNamePhysicalNetBIOS, Name, Edition, ErrorLogPath, IsCaseSensitive, IsClustered,
IsHadrEnabled, IsFullTextInstalled, LoginMode, NetName, PhysicalMemory,
Processors, ServiceInstanceId, ServiceName, ServiceStartMode,
VersionString, Version, DatabaseEngineEdition
$sqlInstance.Information | Select-Object * | fl
$sqlInstance.Properties | Select-Object Name, Value | ft -AutoSize
$sqlInstance.Configuration
-- 15) Set Mail profile
# Set computerName
$computerName = 'TUL1CIPINXDB4'
$srv = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Server("$computerName");
$sm = $srv.Mail.Profiles | Where-Object {$_.Name -eq $computerName};
$srv.JobServer.AgentMailType = 'DatabaseMail';
$srv.JobServer.DatabaseMailProfile = $sm.Name;
$srv.JobServer.Alter();
-- 16) CollectionTime
@{l='CollectionTime';e={(Get-Date).ToString("yyyy-MM-dd HH:mm:ss")}}
-- 17) Out-GridView
Get-Process|Where {$_.cpu -ne $null}|ForEach {New-Object -TypeName psObject -Property @{name=$_.Name;cpu=[double]$_.cpu}}|Out-GridView
-- 18) Move *.sql Files & Folder from Source to Destination
$sServer = 'SrvSource';
$tServer = 'SrvDestination';
$basePath = 'f$\mssqldata'
# Find source folders
$folders = Get-ChildItem "\\$sServer\$basePath" -Recurse | Where-Object {$_.PsIsContainer};
# Create same folders on destination
foreach($fldr in $folders)
{
$newPath = $fldr.FullName -replace "\\\\$sServer\\", "\\\\$tServer\\";
$exists = ([System.IO.Directory]::Exists($newPath));
if($exists) {
Write-Host "Exists=> $newPath" -ForegroundColor Green;
} else {
Write-Host "NotExists=> $newPath" -ForegroundColor Yellow;
#[System.IO.Directory]::CreateDirectory($newPath);
}
#$fldr.FullName -replace "\\\\$sServer\\", "\\\\$tServer\\"
}
# Find source folders
$sqlfiles = Get-ChildItem "\\$sServer\$basePath" -Recurse | Where-Object {$_.PsIsContainer -eq $false} |
Where-Object {$_.Extension -eq '.sql' -or $_.Extension -eq '.bat'};
# Create same folders on destination
foreach($file in $sqlfiles)
{
$newPath = $file.FullName -replace "\\\\$sServer\\", "\\\\$tServer\\";
$exists = ([System.IO.File]::Exists($newPath));
if($exists) {
Write-Host "Exists=> $newPath" -ForegroundColor Green;
} else {
Write-Host "NotExists=> $newPath" -ForegroundColor Yellow;
#Copy-Item "$($file.FullName)" -Destination "$newPath"
}
}
-- 16) Get Inventory Servers on Excel
Import-Module SQLDBATools -DisableNameChecking;
# Fetch ServerInstances from Inventory
$tsqlInventory = @"
select * from Info.Server
"@;
$Servers = (Invoke-Sqlcmd -ServerInstance $InventoryInstance -Database $InventoryDatabase -Query $tsqlInventory | Select-Object -ExpandProperty ServerName);
$SqlInstance = @();
foreach($server in $Servers)
{
$r = Fetch-ServerInfo -ComputerName $server;
$SqlInstance += $r;
}
$SqlInstance | Export-Excel 'C:\temp\TivoSQLServerInventory.xlsx'
-- 17) Group-Object & Measure-Object
$PathOrFolder = 'E:\'
$files = Get-ChildItem -Path $PathOrFolder -Recurse -File | ForEach-Object {
$Parent = (Split-Path -path $_.FullName);
New-Object psobject -Property @{
Name = $_.Name;
FullName = $_.FullName;
Parent = $Parent;
SizeBytes = $_.Length;
}
}
$FolderWithSize = $files | Group-Object Parent | %{
New-Object psobject -Property @{
Parent = $_.Name
Sum = ($_.Group | Measure-Object SizeBytes -Sum).Sum
}
}
-- 18)
<# Script to Find databases which are not backed up in Last 7 Days
#>
$Server2Analyze = 'tul1cipxdb12';
$DateSince = (Get-Date).AddDays(-7) # Last 7 days
# Find Latest Bacukps
$Backups = Get-DbaBackupHistory -SqlInstance $Server2Analyze -Type Full -Since $DateSince #'5/5/2018 00:00:00'
$BackedDbs = $Backups | Select-Object -ExpandProperty Database -Unique
# List of available dbs
$dbs = Invoke-Sqlcmd -ServerInstance $Server2Analyze -Database master -Query "select name from sys.databases" | select -ExpandProperty name;
$NotBackedDbs = @();
foreach($db in $dbs)
{
if($BackedDbs -contains $db){
Write-Host "$db is +nt";
}
else {
$NotBackedDbs += $db;
}
}
Write-Host "Returing Dbs for which backup is not there.." -ForegroundColor Green;
$NotBackedDbs | Add-Member -NotePropertyName ServerName -NotePropertyValue $Server2Analyze -PassThru -Force |
Out-GridView -Title "Not Backed Dbs"
#Remove-Variable -Name NotBackedDbs
-- 19) Import Remove Server Module
$session = New-PSSession -computerName TUL1DBAPMTDB1;
Invoke-Command -scriptblock { Import-Module dbatools } -session $session;
Import-PSSession -module dbatools -session $session;