Download presentation
Presentation is loading. Please wait.
1
Introduction to PowerShell
Focused on SQL Server Piotr Palka
2
Basics of PowerShell Scripting language Command line interpreter
Object oriented (not text based) “Cmdlet”: Verb – noun –parameter Get-Process Get-Help
3
Enable SQL Server integration
Start “PowerShell ISE” Set-ExecutionPolicy -ExecutionPolicy RemoteSigned Requires local admin priviledges Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force No special privileges needed Import-Module SqlServer
4
Variables Sample script: Special variables
$varDate = Get-Date $var1 "***************************" "Day of the year : " + $varDate.DayOfYear $varDate.AddDays(4) Special variables $_ - The current pipeline object $Args – parameters for current function call $Error – last error
5
Comparison Operators 5 > 3 is not comparison in PowerShell!!!!!!!
if ( 5 > 3 ) { "T" } else { "F" } Result: F What happened?
6
Comparison Operators Use instead: if ( 5 -ge 3 ) { "T" } else { "F" } -eq Equal -ne Not equal -ge Greater than or equal -gt Greater than -lt Less than -le Less than or equal And many more…
7
Logical operators -and Logical And -or Logical Or -not logical not
if (( 5 -ge 3 ) -and (5 -eq 4)) { "T" } else { "F" }
8
Basic queries Invoke-Sqlcmd -ServerInstance . -Database TestDB1 -Query "select GetDate()" Demo – accessing query results
9
Iterations ForEach Collections can be created as:
Performs an operation against each item in a collection Collections can be created as: Hardcoded list (in a script), e.g. list of server names Loaded from SQL query Loaded from file ForEach can be used to run scripts on multiple servers/DBs Demo
10
Monitoring and mass actions
For Each database: SELECT physical_name, state, state_desc, size, max_size, growth FROM sys.database_files If file meets logical condition do something: if ($f.size -ge 2000) { Backup file } We can use best of scripting language and SQL
11
Scheduling
12
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.