All SQL Server 2008 installations will automatically have PowerShell. As a SQL Server DBA you will not survive without knowing PowerShell in future. For SQL Server there is a separate component of PowerShel – SQLPS. You start SQLPS in SQL Server or by typing SQLPS in command prompt. SQLPS loads required components which you can work with SQL Server. In the normal PowerShell editor SQL Server related components are not loaded.
Starting SQLPS from SQL Server:
In SQLPS there is a directory structure which you can traverse through that using “cd” which is essentially an alias of Set-Location cmdlet. You can see the directories available in each level by executing “dir” which is another alias for the Get-ChildItem cmdlet.
In the root there are four logical drives or directories as you can see in the above screenshot.
The below screenshot shows that I have traversed through the directory structure upto “tables” object in my local server. Look at the prompt carefully.
Now if you execute “dir” you will get a list of tables available in the AdventureWorks database. You can execute T-SQL commands at this point. For example to get a list of the top 10 tables with the highest number of records.
gci | sort-object -Property RowCount -Desc | select-object schema,name -first 10 | format-table