Select Multiple Tables With Powershell




Import-Module -Name 'SQLPS' -DisableNameChecking
#Assign variables
$Instance   = "MC\MSSQL2014"
 
 
 $myexport="c:\temp\"
 $file="myexportFile.csv"
 
$Server = New-Object Microsoft.SqlServer.Management.SMO.Server("$Instance")

foreach ($database in $Server.databases)
{

if ($database.Name -eq "test1")
{
foreach ($table in $database.tables)
{
[string]$tableName = "$($database.Name)-$($table.schema).$($table.Name)"

if ($table.Name -like "*test*" )
{
$q = @"
select * from  $($table)
"@

Invoke-SqlCmd  -ServerInstance $Server.Name -Database $database.Name -Query $q  |  ConvertTo-Csv  -NoTypeInformation | out-file "$($myexport)$($tableName)$($file)"
}
 
}
 }
 }
 
 


 
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s