I'm trying to create a script for querying a database, extract data and put it to an .csv file. This is the part of interest of the code:
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
###########################
##PRSENTAZIONE DEI RISULTATI##
$table = New-Object System.Data.DataSet
$table.Load($result)
$table | Export-Csv -Path $fileName -Delimiter "|" -NoTypeInformation
I have 2 problems:
On Windows 2003 PowerShell -Delimiter parameter is not present
If I delete that parameter the ouput file presents a wrong format date.
username, ipaddress, yyyy-mm-dd hh:mm:ss (running the same query in Management Studio), username, ipaddress, "dd/mm/yyyy hh.mm.ss" (apexes included ; printing the $table).
How can I solve this?
Related
Currently I have a powershell that was written by someone else. It Connects to SQL and based on a date it will export the results against a Stored procedure...This Works fine Right now.
$FromDate = Read-Host "Enter Date of to Start (YYYY-MM-DD)"
$QueryText = "exec UDO_VW_ExportView_HISTORY #FromDate"
$SqlConnection = new-object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $connString
$SqlCommand = $SqlConnection.CreateCommand()
$SqlCommand.CommandText = "EXEC UDO_VW_ExportView_HISTORY #FromDate"
# Add parameters to pass values to the stored procedure
$SqlCommand.Parameters.AddWithValue("#FromDate", $FromDate) | Out-Null
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCommand
$dataset = new-object System.Data.Dataset
Write-Host $DataAdapter.Fill($dataset) ' records have been exported.'
$dataset.Tables[0] | Export-CSV D:\_#Scripts\Daily_Export_HISTORY\Daily_Report_Txt\MyReport.csv -NoTypeInformation -Force
Write-Host 'New report D:\_#Scripts\Daily_Export_HISTORY\Daily_Report_Txt\MyReport.csv has been successfully generated'
(gc D:\_#Scripts\Daily_Export_HISTORY\Daily_Report_Txt\MyReport.csv) | % {$_ -replace '"""', '"'} | out-file D:\_#Scripts\Daily_Export_HISTORY\Daily_Report_Txt\Daily_Report_For_$FromDate.csv -Fo -En ascii
Remove-Item D:\_#Scripts\Daily_Export_HISTORY\Daily_Report_Txt\MyReport.csv
As you can see (i hope) the first line is:
$FromDate = Read-Host "Enter Date of to Start (YYYY-MM-DD)"
I just want it to get all transactions 7,6,5,4,3,2 days, and Yesterday as one export.
I also see in the code there are declared variables that may also be modified. Can you please look at this coed and provide an updated code that will achieve what I'm trying to do. I'm new to Powershell
Thank you so much!
You can replace :
$FromDate = Read-Host "Enter Date of to Start (YYYY-MM-DD)"
by
$FromDate = ([datetime]::Now).AddDays(-7).Date.ToString("yyyy-MM-dd")
It takes today date and time, remove 7 days, remove time and format it.
$sf = "\\\\domain\\dept\\dcgsi\\Extracts\\Tableau_Unlicensed_Users.csv"
if (Test-Path $sf){
Remove-Item $sf
}
$query = #"
\\copy (SELECT Name
FROM _users
WHERE licensing_role_name = 'Unlicensed')
TO $sf
WITH CSV DELIMITER ','
"#
$conn = New-Object -ComObject ADODB.Connection
# use existing 64 bit ODBC System DSN that we set up manually
$conn.Open('PostgreSQL30')
$conn.Execute($query)
$conn.Close()
I keep getting an error about "\" on the line with the $conn.Execute() when I try and do this. I assume it has to do with character escaping and maybe I am doing it wrong.
Is there a better way to do this with PowerShell if I just need to get the name field of any record from _users and output it to CSV?
Eventually I will be adding more to this to loop through each record in the CSV and execute a tabcmd to remove all the users that are unlicensed.
$sf = "\\domain\dept\dcgsi\Extracts\Tableau_Unlicensed_Users.csv"
if (Test-Path $sf){
Remove-Item $sf
}
$query = #"
SELECT Name
FROM _users
WHERE licensing_role_name = 'Unlicensed'
"#
function Get-ODBC-Data{
$conn = New-Object System.Data.Odbc.OdbcConnection
$conn.ConnectionString = "DSN=PostgreSQL30;"
$conn.Open()
$cmd = New-object System.Data.Odbc.OdbcCommand($query, $conn)
$ds = New-Object system.Data.DataSet
(New-Object System.Data.Odbc.OdbcDataAdapter($cmd)).Fill($ds) | Out-Null
$conn.Close()
$ds.Tables[0] | Export-Csv $sf
}
Get-ODBC-Data
This did like 99% of what I need; I just have to process the csv now and drop the first two lines. The first line is a type info message and the second is the column header.
How can i display the output of a postgresql in powershell. Here is an example:
$query = "SELECT * FROM test where first_name='test'"
function Get-ODBC-Data{
param([string]$query=$(throw 'query is required.'))
$conn = New-Object System.Data.Odbc.OdbcConnection
$conn.ConnectionString = "Driver={PostgreSQL Unicode(x64)};Server=localhost;Port=5432;Database=Test;Uid=test;Pwd=test;"
$conn.open()
$cmd = New-object System.Data.Odbc.OdbcCommand($query,$conn)
$ds = New-Object system.Data.DataSet
(New-Object system.Data.odbc.odbcDataAdapter($cmd)).fill($ds) | out-null
$conn.close()
$ds.Tables[0]
}
function Set-ODBC-Data{
param([string]$query=$(throw 'query is required.'))
$conn = New-Object System.Data.Odbc.OdbcConnection
$conn.ConnectionString= "Driver={PostgreSQL Unicode(x64)};Server=localhost;Port=5432;Database=test;Uid=test;Pwd=test;"
$cmd = new-object System.Data.Odbc.OdbcCommand($query,$conn)
$conn.open()
$cmd.ExecuteNonQuery()
$conn.close()
}
$result = Get-ODBC-Data -query $query
$db = set-odbc-data -query $query
How can i display or fetch values present in the output in a format shown in the screenshot?
How can i export the output to a csv in a proper format?
I didn't test it but try to use below commands as the output from powershell script
C:\Get-Query | Out-GridView
C:\Get-Query | Export-CSV Info.csv
C:\Get-Query | Format-Table -autosize
assuming the script in the file named Get-Query
The solution from this URL
Sorry if I am asking anything that is very basic but I just started PowerShell last night and I'm getting a feel for the new language.
I'm using an export to XLSX script provided by the link below:
https://gallery.technet.microsoft.com/office/Export-XLSX-PowerShell-f2f0c035
I'm also using a simple SQL server pull (SQL_Connection_Script.ps1):
$dataSource = "####"
$user = "####"
$pwd = "####"
$database = "####"
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;"
$query = "Select * from name where id = '1000'"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object “System.Data.DataTable”
$table.Load($result)
$table
$connection.Close()
My issue is when I export this object I get the extra columns: RowError, RowState, Table, ItemArray and HasErrors.
Is there anyway to remove these columns by either a command that I am just unaware of or should I insert a dynamic Select statement, example below?
I am hoping to not have to use a dynamic Select statement if possible.
.\Desktop\SQL_Connection_Script.ps1 | Select $DynamicHeadersHere | Export-XLSX -path .\Desktop\testing123.xlsx -Append
So it looks like my SQL Server Pull function is the thing that is pulling in the extra fields. Any ideas?
After looking around for a while I found I can exclude properties.
.\Desktop\SQL_Connection_Script.ps1 | Select * -ExcludeProperty RowError, RowState, HasErrors, Table, ItemArray | Export-XLSX -path .\Desktop\testing123.xlsx -Append
I am able to run a stored procedure and export it to csv using the following code:
function TestSQLStoredPrc()
{
$connString = "Data Source=xxxxxx,1433;Initial Catalog=TestDB;User Id=TestUser; Password=YYYYYYY;"
$Reference = Read-Host "Enter Name";
$QueryText = "exec dbo.GetUsersCountByName 'Test'";
$SqlConnection = new-object System.Data.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = $connString;
$SqlCommand = $SqlConnection.CreateCommand();
$SqlCommand.CommandText = "EXEC dbo.GetUsersCountByName 'Test'";
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCommand
$dataset = new-object System.Data.Dataset
Write-Host $DataAdapter.Fill($dataset) ' records have been exported.'
$dataset.Tables[0] | Export-CSV C:\MyReport.csv -Force -NoTypeInformation
Write-Host 'New report C:\MyReport.csv has been successfully generated'
}
TestSQLStoredPrc
I am able to get a csv file as output. But I need to apply background color and formatting to the header column of the output csv file.
Can anyone help me to resolve this issue by providing some sample example.
Thanks & Regards,
Santosh Kumar Patro
You can format it and save it as HTML, but you cannot do that and have it remain a .csv file. CSV is, by definition plaint text - there is no provision for storing foratting information in the file, only header names and values.