Skip to content

Commit 59a5b01

Browse files
2 parents b947116 + 59271cb commit 59a5b01

4 files changed

+523
-0
lines changed

Backup-OLADatabase.ps1

+183
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
<#
2+
.Synopsis
3+
To perform an ad-hoc backup using OLA Hallengrens solution
4+
.DESCRIPTION
5+
This function will perform an ad-hoc backup using OLA Hallengrens solution - It doesnot expose all of the
6+
capabilities but is useful for quick backups when needed
7+
Note the Database paramter is dynamically filled once you type it
8+
.EXAMPLE
9+
Backup-OlaDatabase -instance SERVERNAME -Type LOG -Share \\backupshare -Database Database
10+
11+
This will perform a LOG backup of the Database database on the SERVERNAME instance to the \\backupshare Share.
12+
Note the Database paramter is dynamically filled once you type it
13+
.EXAMPLE
14+
Backup-OlaDatabase -instance SERVERNAME -Type FULL -Share X:\backups -Database Database
15+
16+
This will perform a FULL backup of the Database database on the SERVERNAME instance to the X:\backups Share.
17+
Note the Database paramter is dynamically filled once you type it
18+
.EXAMPLE
19+
Backup-OlaDatabase -instance SERVERNAME -Type DIFF -Share \\TheShareForBackups -Database Database -OutputResults
20+
21+
This will perform a DIFF backup of the Database database on the SERVERNAME instance to the \\TheShareForBackups
22+
Share and output the message to the screen.
23+
Note the Database paramter is dynamically filled once you type it
24+
.NOTES
25+
26+
IF YOU HAVE THE STORED PROCEDURE IN A DIFFERENT DATABASE - You will need to alter line 130
27+
28+
AUTHOR - Rob Sewell https://sqldbawithabeard.com
29+
DATE - 27/10/2016
30+
#>
31+
function Backup-OlaDatabase
32+
{
33+
[CmdletBinding( SupportsShouldProcess=$true,
34+
PositionalBinding=$false,
35+
ConfirmImpact='Medium')]
36+
[Alias()]
37+
Param
38+
(
39+
# The Server/instance
40+
[Parameter(Mandatory=$true,HelpMessage='This is the Instance that the database is on',
41+
ValueFromPipeline=$true,
42+
ValueFromPipelineByPropertyName=$true,
43+
ValueFromRemainingArguments=$false,
44+
Position=0)]
45+
[ValidateNotNull()]
46+
[ValidateNotNullOrEmpty()]
47+
[string]$Instance,
48+
# The Server/instance
49+
[Parameter(Mandatory=$true,HelpMessage='This is the type of backup',
50+
ValueFromPipeline=$true,
51+
ValueFromPipelineByPropertyName=$true,
52+
ValueFromRemainingArguments=$false,
53+
Position=2)]
54+
[ValidateNotNull()]
55+
[ValidateNotNullOrEmpty()]
56+
[ValidateSet('FULL', 'DIFF', 'LOG')]
57+
[string]$Type,
58+
59+
60+
# The Share
61+
[Parameter(Mandatory=$true,HelpMessage='This is the root of the backup directory',
62+
ValueFromPipeline=$true,
63+
ValueFromPipelineByPropertyName=$true,
64+
ValueFromRemainingArguments=$false,
65+
Position=2)]
66+
[ValidateNotNull()]
67+
[ValidateNotNullOrEmpty()]
68+
[String]$Share,
69+
70+
#If you wish to see the results of the query
71+
[switch]$OutputResults,
72+
73+
# Compression off ?
74+
[switch]$CompressionOff,
75+
76+
# Copy Only ?
77+
[switch]$CopyOnly
78+
79+
)
80+
81+
82+
DynamicParam {
83+
# Set the dynamic parameters' name
84+
$ParameterName = 'Database'
85+
86+
# Create the dictionary
87+
$RuntimeParameterDictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary
88+
89+
# Create the collection of attributes
90+
$AttributeCollection = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute]
91+
92+
# Create and set the parameters' attributes
93+
$ParameterAttribute = New-Object -TypeName System.Management.Automation.ParameterAttribute
94+
$ParameterAttribute.Mandatory = $true
95+
$ParameterAttribute.Position = 1
96+
97+
# Add the attributes to the attributes collection
98+
$AttributeCollection.Add($ParameterAttribute)
99+
100+
# Generate and set the ValidateSet
101+
# Load the assembly
102+
[void][reflection.assembly]::LoadWithPartialName( 'Microsoft.SqlServer.Smo' )
103+
104+
$srv = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $Instance
105+
$arrSet = $Srv.databases.Name
106+
$srv.ConnectionContext.Disconnect()
107+
$ValidateSetAttribute = New-Object -TypeName System.Management.Automation.ValidateSetAttribute -ArgumentList ($arrSet)
108+
109+
# Add the ValidateSet to the attributes collection
110+
$AttributeCollection.Add($ValidateSetAttribute)
111+
112+
# Create and return the dynamic parameter
113+
$RuntimeParameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter -ArgumentList ($ParameterName, [string], $AttributeCollection)
114+
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
115+
return $RuntimeParameterDictionary
116+
}
117+
118+
begin {
119+
# Bind the parameter to a friendly variable
120+
$Database = $PsBoundParameters[$ParameterName]
121+
122+
if($CompressionOff)
123+
{
124+
$Compression = 'N'
125+
}
126+
else
127+
{
128+
$Compression = 'Y'
129+
}
130+
if($CopyOnly)
131+
{
132+
$Co = 'Y'
133+
}
134+
else
135+
{
136+
$CO = 'N'
137+
}
138+
}
139+
Process
140+
{
141+
142+
$Query = @"
143+
EXECUTE [master].[dbo].[DatabaseBackup]
144+
@Databases = '$Database',
145+
@Directory = N'$Share',
146+
@BackupType = '$Type',
147+
@Verify = 'Y',
148+
@CheckSum = 'Y',
149+
@Compress= '$Compression',
150+
@LogToTable = 'Y',
151+
@CopyOnly = '$CO'
152+
"@
153+
154+
if ($pscmdlet.ShouldProcess("$Instance" , "Back up $Database"))
155+
{
156+
try
157+
{
158+
$srv = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $Instance
159+
$SqlConnection = $srv.ConnectionContext
160+
if($OutputResults)
161+
{
162+
Register-ObjectEvent -InputObject $SqlConnection -EventName InfoMessage -SupportEvent -Action {
163+
Write-Host $Event.SourceEventArgs
164+
}
165+
}
166+
$SqlConnection.StatementTimeout = 8000
167+
$SqlConnection.ConnectTimeout = 10
168+
$SqlConnection.Connect()
169+
$SqlConnection.ExecuteNonQuery($Query)
170+
Write-Output -InputObject "$Database has been backed up to $Share"
171+
}
172+
catch
173+
{
174+
Write-Warning -Message ("Something went Wrong. Run `$Error[0] | Fl -force to work out why")
175+
$Query
176+
}
177+
}
178+
}
179+
End
180+
{
181+
$srv.ConnectionContext.Disconnect()
182+
}
183+
}

Get-SQLAgentJobDuration.ps1

+152
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
<#PSScriptInfo
2+
3+
.VERSION 1.0
4+
5+
.GUID 5ebeb3ec-36b0-4dad-a3e3-bbff1ffcbfd7
6+
7+
.AUTHOR Rob Sewell
8+
9+
.COMPANYNAME Sewells Consulting
10+
11+
.COPYRIGHT Rob Sewell - please credit Rob Sewell - https://sqldbawithbeard.com if used
12+
13+
.DESCRIPTION Returns the Job Duration for an agent job on an instance
14+
15+
.TAGS SQL,SQL Agent Jobs, Duration
16+
17+
.LICENSEURI
18+
19+
.PROJECTURI
20+
21+
.ICONURI
22+
23+
.EXTERNALMODULEDEPENDENCIES sqlserver
24+
25+
.REQUIREDSCRIPTS
26+
27+
.EXTERNALSCRIPTDEPENDENCIES
28+
29+
.RELEASENOTES Initial
30+
#>
31+
#Requires -Module sqlserver
32+
Function Get-SQLAgentJobDuration
33+
{
34+
<#
35+
.Synopsis
36+
Returns the Job Duration for an agent job on an instance or number of instances with the Job Names provided dynamically
37+
.DESCRIPTION
38+
This function returns the Job Duration for an agent job on an instance or number of instances with the Job Names provided dynamically
39+
It can also output to CSV and prompt if youwould like to open the file
40+
.EXAMPLE
41+
Get-SQLAgentJobDuration -Instances SERVER -JobName 'Job must run quickly'
42+
43+
This will return the servername. jobname, rundate and duration of the 'Job must run quickly' job on the Instance SERVER
44+
.EXAMPLE
45+
Get-SQLAgentJobDuration -Instances SERVER -JobName 'Job must run quickly' -CSV
46+
47+
This will output the servername. jobname, rundate and duration of the 'Job must run quickly' job on the Instance SERVER into a CSV file
48+
located in the Users MyDocuments folder named JobName_Date_Time.csv
49+
.EXAMPLE
50+
Get-SQLAgentJobDuration -Instances SERVER -JobName 'Job must run quickly' -CSV -Path c:\temp
51+
52+
This will output the servername. jobname, rundate and duration of the 'Job must run quickly' job on the Instance SERVER into a CSV file
53+
located in C:\Temp named JobName_Date_Time.csv
54+
.NOTES
55+
AUTHOR - Rob Sewell https://sqldbawithabeard.com
56+
DATE - 30/10/2016
57+
#>
58+
#Requires -Version 5
59+
#Requires -Module sqlserver
60+
param
61+
(# The Server/instance
62+
[Parameter(Mandatory=$true,HelpMessage='The Instance',
63+
ValueFromPipeline=$true,
64+
ValueFromPipelineByPropertyName=$true,
65+
ValueFromRemainingArguments=$false,
66+
Position=0)]
67+
[ValidateNotNull()]
68+
[ValidateNotNullOrEmpty()]
69+
[object]$Instances,
70+
# CSV required
71+
[Parameter(Mandatory=$false,HelpMessage='Want to output to CSV')]
72+
[switch]$CSV,
73+
# Path for CSV
74+
[Parameter(Mandatory=$false,HelpMessage='Path for CSV')]
75+
[object]$Path
76+
)
77+
DynamicParam {
78+
# Set the dynamic parameters' name
79+
$ParameterName = 'JobName'
80+
81+
# Create the dictionary
82+
$RuntimeParameterDictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary
83+
84+
# Create the collection of attributes
85+
$AttributeCollection = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute]
86+
87+
# Create and set the parameters' attributes
88+
$ParameterAttribute = New-Object -TypeName System.Management.Automation.ParameterAttribute
89+
$ParameterAttribute.Mandatory = $true
90+
$ParameterAttribute.Position = 1
91+
92+
# Add the attributes to the attributes collection
93+
$AttributeCollection.Add($ParameterAttribute)
94+
95+
# Generate and set the ValidateSet
96+
$arrSet = (Get-SQLAgentJob -ServerInstance $Instances).Name
97+
$ValidateSetAttribute = New-Object -TypeName System.Management.Automation.ValidateSetAttribute -ArgumentList ($arrSet)
98+
99+
# Add the ValidateSet to the attributes collection
100+
$AttributeCollection.Add($ValidateSetAttribute)
101+
102+
# Create and return the dynamic parameter
103+
$RuntimeParameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter -ArgumentList ($ParameterName, [string], $AttributeCollection)
104+
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
105+
return $RuntimeParameterDictionary
106+
}
107+
108+
begin {
109+
# Bind the parameter to a friendly variable
110+
$JobName = $PsBoundParameters[$ParameterName]
111+
$FormattedDuration = @{Name = 'FormattedDuration';Expression = {[timespan]$_.RunDuration.ToString().PadLeft(6,'0').insert(4,':').insert(2,':')}}
112+
}
113+
Process {
114+
$JObs = (Get-SQLAgentJobHistory -ServerInstance $Instances).Where{$_.JoBName -eq $JobName}
115+
$Result = $Jobs.Where{$_.Stepid -eq 0} | Select Server, JobName,RunDate,$FormattedDuration
116+
}
117+
End {
118+
if($CSV)
119+
{
120+
if(!$Path)
121+
{
122+
$docs = [Environment]::GetFolderPath("mydocuments")
123+
$Path = $Docs
124+
}
125+
126+
$Date = Get-Date -Format yyyyMMdd_HHmmss
127+
$FilePath = $Path + '\' + $jobname + '_' + $Date + '.csv'
128+
$Result | Export-Csv -Path $FilePath -NoTypeInformation
129+
130+
# Prompt to create and then create.
131+
$title = "Want to Open the file??"
132+
$message = "Would you like to open the CSV file now? (Y/N)"
133+
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Will continue"
134+
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Will exit"
135+
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
136+
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
137+
138+
if ($result -eq 1)
139+
{
140+
return "OK File is located at $FilePath"
141+
}
142+
else
143+
{
144+
Invoke-Item -Path $FilePath
145+
}
146+
}
147+
else
148+
{
149+
$Result
150+
}
151+
}
152+
}

0 commit comments

Comments
 (0)