PowerShell to fetch a SQL Execution Plan

With PowerShell becoming the scripting language of choice for many people, I've occasionally wondered about using it to analyse execution plans. After all, an execution plan is just XML, and PowerShell is just one tool which will very easily handle xml.

The thing is – there's no Get-SqlPlan cmdlet available, which has frustrated me in the past. Today I figured I'd make one.

I know that I can write T-SQL to get an execution plan using SET SHOWPLAN_XML ON, but the problem is that this must be the only statement in a batch. So I used go, and a couple of newlines, and whipped up the following one-liner:


function Get-SqlPlan([string] $query, [string] $server, [string] $db)       
{ return ( (invoke-sqlcmd -MaxCharLength 9999999 -Server $server -Database $db -Query &quot;set showplan_xml on;<code>ngo</code>n$query&quot;).Item( 0)) }  

(but please bear in mind that I have the SQL Snapins installed, which provides invoke-sqlcmd)

To use this, I just do something like:


$plan = get-sqlplan "select name from Production.Product" "." "AdventureWorks"  

And then find myself with an easy way to navigate through an execution plan!


At some point I should make the function more robust, but this should be a good starter for any SQL PowerShell enthusiasts (like Aaron Nelson) out there.

4 thoughts on “PowerShell to fetch a SQL Execution Plan”

  1. Hi
    thanks for the script, however e.g. trying to get the plan for AdventureWorks2012.dbo.uspGetBillOfMaterials I get
    Error: "Unexpected end of file has occurre
    d. The following elements are not closed: OutputList, RelOp, QueryPlan, StmtSimple, Statements, Stor
    edProc, StmtSimple, Statements, Batch, BatchSequence, ShowPlanXML. Line 1, position 4001."
    At D:\Projekte\Wincasa\QVReporting_home\CreateExecutionPlan.ps1:6 char:109
    + { return ([xml] (invoke-sqlcmd -Server $server -Database $db -Query "set showplan_xml on;ngon$qu
    ery").Item <<<< ( 0)) }
       + CategoryInfo          : NotSpecified: (:) [], RuntimeException
       + FullyQualifiedErrorId : RuntimeException
    any idea?

  2. Hi juerg,
    Make sure the file contains the right combinations of brackets, braces and parentheses, and has no extra characters in there.

  3. Oh Juerg,
    The error you got is just because the plan is larger than the 4000 characters that are being returned. If you use "-MaxCharLength 9999999" this should work better.

Leave a Reply

Your email address will not be published. Required fields are marked *