Color coding Invoke-SQL in Powershell - sql

Using invoke-sql I have a PowerShell script that returns results from a SQL Query. That query has the status of several data points local I want to colour code the entire row if the column of Status returns different values. Is this possible as I know you can colour code Charts in PowerShell but not sure how a larger return query would work?
param(
[string] $dataSource = "SQLName",
[string] $database = "DatabaseName",
[string] $sqlCommand = $("Select tbldatafeed.datafeed_name,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(tbldatafeedhistory.status_id,1,'Running'),2,'Completed'),3,'Faulted'),4,'Warning'),5,'Terminating'),6,'Terminated'),7,'Pending') AS Status,DateDiff(MINUTE,tbldatafeedhistory.start_time, tbldatafeedhistory.end_time) As 'Run Time(minutes)'
from tblDataFeedHistory
left Join tblDatafeed on tbldatafeedhistory.datafeed_id = tbldatafeed.datafeed_id
inner join
(
Select max(start_time) as LatestDate, [datafeed_id]
from tblDataFeedHistory
Group by datafeed_id
) SubMax
on tblDataFeedHistory.start_time = SubMax.LatestDate
and tblDataFeedHistory.datafeed_id = SubMax.datafeed_id
WHERE tbldatafeed.is_active = 1
Order by tbldatafeed.datafeed_id")
)
$connectionString = "Data Source=$dataSource; " + "Integrated Security=SSPI; " + "Initial Catalog=$database"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
write-output $adapter.Fill($dataSet) | Out-Null
$connection.Close()
$dataSet.Tables
}
$FeedID = Invoke-SQL
$FeedID
The output would be a red highlighted line if the column returned Failed, yellow if the Column returns Warning, Green if the column returns Completed.

I've not personally found or seen a reason to do this with SQL data generally, nor do I have any record in my stash of anyone who has.
Anything you write to the screen can have color. It's one of the primary focuses of the …
[Write-Host][1]
Or
[Console]::ForegroundColor]
... cmdlet or .Net class.
However, if you plan to use that data on the pipeline, or elsewhere, then don't use it. Especially if you are not on the newest PowerShell versions. Legacy PowerShell, Write-Host empties the buffer, later PowerShell versions, send it to the Information Stream. As talked by PowerShell inventor Jeffery Snover here:.
http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful
... Jeffrey Snover change his stance on this as of May 2016.
With PowerShell v5 Write-Host no longer "kills puppies". data is
captured into info stream ...
https://twitter.com/jsnover/status/727902887183966208
https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Write-Information?view=powershell-5.1
However, there are PowerShell modules you can leverage to get really creative with color.
Find-Module -Name '*color*' | Format-Table -AutoSize
You also have several scripts to leverage as is or tweak for your use case.
Format Table Colors in PowerShell
Format the output table colors in PowerShell host with/without conditional colorful formatting.
Download : Write-PSObject.ps1
You do have another option. If you want to call attention, with color to a given screen output line, you can use the ...
Write-Warning
Write-Error
... cmdlets and just accept its default color.
Yet, your question could almost be a duplicate of these Q&A and its accepted answer.
Powershell - Output Color for certain results
Is there a way to specify a font color when using write-output
If you are saying, that you are sending this to a form, then you have to handle color in the form properties code.

Related

How to add value comma-separated parameter calling SQL query using SQLCMD via Powershell

I'm writing a PowerShell script that makes a call with SQLCMD to execute a .sql file and output a CSV file. In SQLCMD command, I want to pass a parameter back to query that includes a value of comma-separated list so I can use in an 'IN' statement.
select a, b, c, d
from dbtbl (nolock)
where client_id in ($(clients))
The SQLCMD command works if I assign $client_id to a singular value i.e. '000_abc' but does not work if I assign the variable as an array. i.e. '000_abc','000_def', '000_ghi'
# Input variables
$SQLSourceFolder = "V:\PS\queries\"
$FolderFile = "V:\PS\Myoutput.csv"
$TaxCode = "MY*script*.sql"
$qtr = "'1'"
$year = "'2019'"
#Works Fine. Only one client filtered in SQL query where clause
$client_id = "'000_abc'"
#Doesn't Work. Multiple clients filtered in SQL query where clause with IN statement.
# $client_id = "'000_abc','000_def', '000_ghi'"
# Find all files matching $TaxCode filter in the folder specified
Get-ChildItem -Path $SQLSourceFolder -Filter $TaxCode | ForEach-Object {
cls
Start-Process "D:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\SQLCMD.EXE" -ArgumentList #("-S","tcp:XXXXXXXXXXXXXX,1433", "-d" ,"XXX", "-U", "XXXXXXXX", "-P" ,"XXXXXXXXXX", " -v", " qtr = $qtr", " yr = $year", " clients = $client_id", " -W ", "-s", "~", "-i", "$($_.FullName)", "-o", "$FolderFile")
}
The expected result would be to pass multi-value variable to sql query where parameter is used in where clause with IN statement.
How come you're using sqlcmd.exe instead of Invoke-SqlCmd or, better yet, Invoke-SqlCmd2?
Quick context: Invoke-SqlCmd2 is a community drop-in replacement for Invoke-SqlCmd which addresses a few issues. It's widely considered the best solution for querying MS SQL from PS. Relevant: Install-Module Invoke-SqlCmd2, https://github.com/sqlcollaborative/Invoke-SqlCmd2
As you are discovering, passing arguments in to native applications is surprisingly difficult. It's always better to use PS commands where possible, in my experience.
Let me know if there's a good reason not to use Invoke-SqlCmd2 and I'll see what I can do to mock this for you, but it's a non-trivial effort on my part, so I do encourage you to just follow normal practice!

Generate data seeding script using PowerShell and SSMS

Here I found a solution for the manual creation of the data seeding script. The manual solution allows me to select for which tables I want to generate the inserts
I would like to know if there is an option to run the same process via PowerShell?
So far I have managed how to create a SQL script which creates the Database schema seeder:
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') "(localdb)\mssqlLocalDb"
$dbs=$s.Databases
#$dbs["HdaRoot"].Script()
$dbs["HdaRoot"].Script() | Out-File C:\sql-seeding\HdaRoot.sql
#Generate script for all tables
foreach ($tables in $dbs["HdaRoot"].Tables)
{
$tables.Script() + "`r GO `r " | out-File C:\sql-seeding\HdaRoot.sql -Append
}
however is there any similar way to generate the data seeding script?
Any ideas? Cheers
You can use the SMO scripter class. This will allow you to script the table creates as well as INSERT statements for the data within the tables.
In my example I'm directly targeting TempDB and defining an array of table names I want to script out rather than scripting out every table.
Scripter has a lot of options available, so I've only done a handful in this example - the important one for this task is Options.ScriptData. Without it you'll just get the schema scripts that you're already getting.
The EnumScript method at the end does the actual work of generating the scripts, outputting, and appending the script to the file designated in the options.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
## target file
$outfile = 'f:\scriptOutput.sql'
## target server
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') "localhost"
## target database
$db = $s.databases['tempdb']
## array of tables that we want to check
$tables = #('Client','mytable','tablesHolding')
## new Scripter object
$tableScripter = new-object ('Microsoft.SqlServer.Management.Smo.Scripter')($s)
##define options for the scripter
$tableScripter.Options.AppendToFile = $True
$tableScripter.Options.AllowSystemObjects = $False
$tableScripter.Options.ClusteredIndexes = $True
$tableScripter.Options.Indexes = $True
$tableScripter.Options.ScriptData = $True
$tableScripter.Options.ToFileOnly = $True
$tableScripter.Options.filename = $outfile
## build out the script for each table we defined earlier
foreach ($table in $tables)
{
$tableScripter.enumscript(#($db.tables[$table])) #enumscript expects an array. this is ugly, but it gives it what it wants.
}

Powershell: SQL Server Management Studio Script Generator

I use the Script Generator which is integrated in the Microsoft SQL Server Management Studio to generate an import script for a whole database.
I have to do some replacements in the script which I do with Powershell. Now I want to automate the generation. Is there a way to execute exactly this Script Generator Tool (and setting some options as on the screenshot - in my case 'Data only')? Or (if this isn't possible) can I open this tool window automatically from a ps script so I don't have to open the Management Studio, selecting the DB, ...?
I found some scripts which 'manually' build the script file in Powershell but that's not exactly what I'm looking for.
Thanks!
This question's been here awhile and you've probably found your answer by now, but for those looking for a simple way to do this, the current versions of SQL server Powershell modules have native commands and methods that support this functionality from SMO.
You can use Get-SqlDatabase and methods such as .Script() and .EnumScript().
For example, this will generate CREATE scripts for user defined functions and save it to file:
$Database = Get-SqlDatabase -ServerInstance $YourSqlServer -Name $YourDatabaseName
$MyFuncs = $Database.UserDefinedFunctions | Where Schema -eq "dbo"
$MyFuncs.Script() | Out-File -FilePath ".\SqlScripts\MyFunctions.sql"
If you want to script data and elements like indexes, keys, triggers, etc. you will have to specify the scripting options, like this:
$scriptOptions = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$scriptOptions.NoCollation = $True
$scriptOptions.Indexes = $True
$scriptOptions.Triggers = $True
$scriptOptions.DriAll = $True
$scriptOptions.ScriptData = $True
$Database.Tables.EnumScript($scriptOptions) | Out-File -FilePath ".\AllMyTables.sql"
Note that the Script() method doesn't support scripting data. Use EnumScript() for tables.
If you want to script data only, as asked, you can try $scriptOptions.ScriptData = $True and $scriptOptions.ScriptSchema = $False.

Script out all SQL objects under particular schema

Is there any way I can script out all the SQL Server objects (tables, SP, functions etc) under a schema?
In our database we have a table containing name of all the schemas and there are more than 500 schema. Some of them are for dev and some are prod. I need to script out all the objects under dev schema and create a new database.
ApexSQL Script is the tool which can be very helpful in this situation. It is the tool which creates SQL scripts for database objects, and it can script all objects into one script or all objects separately.
For this situation here is what you should do:
Select server and the database which you want to script and load them.
Go to the View tab and click the “Object filter” button, then select the “Edit filter” button:
In the Filter editor for all objects select the “Include if:” and “Click here to add filter criteria”:
Select the “Schema”, “Equals” and Enter the desired schema name, then click OK:
Click on the Home tab, check all objects and Click the “Script” button:
In the third step of the Synchronization wizard, under the Script file tab, select if you want to create one script for all objects or for each object individually from the Granularity drop down menu:
In the last step of the Script wizard click the Create button and check out the results – you will have the script which can be executed in the SQL Server Management Studio.
Thanks guys for your reply. I have solved this by generating all the scripts through SSMS and then created a schema only database. Than I dropped all the tables, views SP, functions etc those are not part of the schema I do not need.
It took me around 20 mins to do that. But after all the work is done.
This is PowerShell answer to your problem.
$Server= 'SERVER_NAME'
$Database= 'DATABASE_NAME'
$SmoScriptPath = 'SCRIPT_OUTPUT.SQL'
$Schemas = #("dlo", "deo") # include objects that fall under this schema set
$ObjectTypes = #("StoredProcedures", "Views", "Tables") #object types to be included
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.Data") | Out-Null
$SmoServer = new-object "Microsoft.SqlServer.Management.SMO.Server" $Server
$SmoServer.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject")
$SmoDb = New-Object "Microsoft.SqlServer.Management.SMO.Database"
$SmoDb = $SmoServer.Databases[$Database]
$SmoScr = New-Object "Microsoft.SqlServer.Management.Smo.Scripter"
$SmoScr.Server = $SmoServer
$SmoScr.Options = New-Object "Microsoft.SqlServer.Management.SMO.ScriptingOptions"
$SmoScr.Options.AllowSystemObjects = $false
$SmoScr.Options.IncludeDatabaseContext = $true
$SmoScr.Options.IncludeIfNotExists = $false
$SmoScr.Options.ClusteredIndexes = $true
$SmoScr.Options.Default = $true
$SmoScr.Options.DriAll = $true
$SmoScr.Options.Indexes = $true
$SmoScr.Options.NonClusteredIndexes = $true
$SmoScr.Options.IncludeHeaders = $false
$SmoScr.Options.ToFileOnly = $true
$SmoScr.Options.AppendToFile = $true
$SmoScr.Options.ScriptDrops = $false
$SmoScr.Options.Triggers = $true
$SmoScr.Options.ExtendedProperties = $true
$SmoScr.Options.FileName = $SmoScriptPath
New-Item $SmoScr.Options.FileName -type file -force | Out-Null
Foreach ($ObjectType in $ObjectTypes) {
$Objects = $SmoDb.$ObjectType | where {$_.IsSystemObject -eq $false -and $Schemas.Contains($_.Schema)}
Foreach ($Object in $Objects | where {$_ -ne $null})
{
$SmoScr.Script($Object)
}
}
If you are looking for a solution for getting these objects scripted on a schedule and checked into a GIT Repo Automatically.
Check out the following project I have shared: https://github.com/Drazzing/mssqlobjectstogit
What you get:
Changes to MS SQL Objects over time in [GIT]
Report that shows who Added / Deleted / Changed the objects over time [CSV]
Report Example:
You can use Redgate SQL Compare
or
use management studio generate script feature.

Run sqlquery on multiple server using Powershell

I am trying to run this query
select mirroring_role_desc from sys.database_mirroring where database_id > 4 and mirroring_state is NOT NULL
So the query will basically output the number of databases and just show principal/mirror
like this
I want this query to output to excel file another interesting thing, if any one database in the instance is prinicial/mirror then we can assume the whole instance as principal/mirror.
So in the excel file I want one column with servername\hostname and then the next column to show if it is mirror or principal or none (if none just leave blank) How to do this?
I have tried this,
$ServerInstance = "server1\instance1a "
$Database = " "
$ConnectionTimeout = 30
$Query = "select mirroring_role_desc from sys.database_mirroring where database_id > 4 and mirroring_state is NOT NULL"
$QueryTimeout = 120
$conn=new-object System.Data.SqlClient.SQLConnection
$ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout
$conn.ConnectionString=$ConnectionString
$conn.Open()
$cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
$cmd.CommandTimeout=$QueryTimeout
$ds=New-Object system.Data.DataSet
$da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
[void]$da.fill($ds)
$conn.Close()
$ds.Tables
frankly the above code is working fine but the problem is getting the instance name and only single column with principal/mirror INTO a excel file, that is the issue that I am having.
To get a better idea this is what I am trying to achieve:
I wrote a blog post a while back to run a script across all servers in a central management server. You should be able to adapt it fairly easily. Check it out here.