Introduction to PowerShell Focused on SQL Server Piotr Palka
Basics of PowerShell Scripting language Command line interpreter Object oriented (not text based) “Cmdlet”: Verb – noun –parameter Get-Process Get-Help
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
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
Comparison Operators 5 > 3 is not comparison in PowerShell!!!!!!! if ( 5 > 3 ) { "T" } else { "F" } Result: F What happened?
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…
Logical operators -and Logical And -or Logical Or -not logical not if (( 5 -ge 3 ) -and (5 -eq 4)) { "T" } else { "F" }
Basic queries Invoke-Sqlcmd -ServerInstance . -Database TestDB1 -Query "select GetDate()" Demo – accessing query results
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
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
Scheduling
Questions?