0

I want to format the the output from a sql query that is run in powershell.

The script I have right now is very basic:

sqlcmd -S {Server} -d (Database) -b -Q "sp_whoisactive" | format-table

Ideally I would like to ensure that the output is in a readable format such as

Column 1        Column 2        Column 3
Data            Data2           Data3

However right now the data is all over the place and impossible to read and does not include any of the column names.

How I can accomplish this?

4
  • 1
    Please add the code you have tried. Commented Mar 6, 2017 at 22:36
  • 1
    Possible duplicate of Formatting powershell SQL Server output into columns and rows Commented Mar 6, 2017 at 22:38
  • Please provide the code you are using and the result it is returning, then provide how you would want it to appear like. This will help us in assisting your needs appropriately. Commented Mar 7, 2017 at 10:25
  • Ive updated the description to try to include more info Commented Mar 7, 2017 at 20:39

1 Answer 1

1

Powershell does not know how to handle output from sqlcmd. Instead use Invoke-Sqlcmd which is tailored to the inner workings of Powershell and can pass data as objects which can be manipulated.

If you call Invoke-Sqlcmd with a query it will list the results in a linear fashion which is not what you want. To get the format of a tabular view of the data, do again as you attempted with the sqlcmd...pipe the output into Format-Table.

Here is the command to use

Invoke-Sqlcmd -Server '{Server Name}'   '
              -Database {DatabaseName}  '
              -query "Select * from MyTable" | Format-Table
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer thanks @ΩmegaMan - you might want backticks at the end of each multiline?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.