I have a PowerShell script that connects to a DB and loops over some data.
After the script finishes or throws an error, I need to append whatever the text displayed in the console to a log file.
I couldn't achieve that using Write-Output
because I don't want to save specific values, I just need the whole console text to be appended to a file.
Thank you.
EDIT :
In fact, the final result that I'm looking for, is a log file with timestamps, here is my code :
$server = "USER\SQLEXPRESS"
$database = "database_test"
$tablequery = "SELECT name from sys.tables"
#Delcare Connection Variables
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $tablequery
$command.Connection = $connection
#Load up the Tables in a dataset
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()
$DriveName = (get-location).Drive.Name
$extractDir = md -Force "$($DriveName):\csv\files"
# Loop through all tables and export a CSV of the Table Data
foreach ($Row in $DataSet.Tables[0].Rows)
{
$connection.open();
#Specify the output location of your dump file
$command.CommandText = "SELECT * FROM [$($Row[0])]"
$command.Connection = $connection
(Get-Culture).NumberFormat.NumberDecimalSeparator = '.'
(Get-Culture).DateTimeFormat.ShortDatePattern = 'yyyy-MM-dd'
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()
$extractFile = "$($extractDir)\$($Row[0]).csv"
$DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation -Encoding UTF8
}
I need to print each filename exported to csv ( $extractFile
) with a timestamp in a log file, and then if an error occurs, I need to print that too with a timestamp, and so on till the script finishes.
You could use Start-Transcript for debugging purposes:
Start-Transcript -path "C:\temp\myTranscript.txt"
Add at the start of your script and get all the console output written into C:\\temp\\myTranscript.txt
You can do this with Start-Transcript
, try
/ catch
/ finally
, or writing your own code (to store the console output to a variable, and append a text file with the contents when required). Note the -Append
parameter with Start-Transcript
.
Without code, it's difficult to know which of these to recommend.
Now that you've added some code, see some additional info on each method. I'm not familiar with SQL via PowerShell so not sure what kind of output/errors you will be getting (regarding errors, specifically if there are terminating or non-terminating)
Transcript
Start-Transcript
should go at the beginning, and Stop-Transcript
at the end. This will log whatever is normally displayed on the console. Running Start-Transcript
while a transcript is already being recorded will lead to a nasty error.
Start-Transcript -Path "c\temp\mylogfile.txt"
$server = "USER\SQLEXPRESS"
$database = "database_test"
$tablequery = "SELECT name from sys.tables"
...
...
$extractFile = "$($extractDir)\$($Row[0]).csv"
$DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation -Encoding UTF8
}
Stop-Transcript
Terminating Errors
Add try
/ catch
/ finally
as appropriate. You can be lazy and add this over the whole code, or do it properly and wrap the parts that could lead to terminating errors .
...
foreach ($Row in $DataSet.Tables[0].Rows)
{
try{
$connection.open();
#Specify the output location of your dump file
...
...
...
$extractFile = "$($extractDir)\$($Row[0]).csv"
$DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation -Encoding UTF8
}catch{
# what to do if there is a terminating error
}finally{
# what to do whether there is an error or not
if(Test-Path "$($extractDir)\$($Row[0]).csv"){
# simple check: if a file was created, no error... right?
"$(Get-Date -f 'yyyy-MM-dd hh:mm:ss') $($Error[0])" | Out-File "c:\temp\mylogfile.txt" -Append
}else{
"$(Get-Date -f 'yyyy-MM-dd hh:mm:ss') $extractFile" | Out-File "c:\temp\mylogfile.txt" -Append
}
}
}
...
No Terminating Errors
Just add a line to export errors. Ensure you clear the automatic variable $Error
each loop
...
foreach ($Row in $DataSet.Tables[0].Rows)
{
$Error.Clear()
$connection.open();
#Specify the output location of your dump file
...
...
...
$extractFile = "$($extractDir)\$($Row[0]).csv"
$DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation -Encoding UTF8
# if there are no errors, write filename. Otherwise write errors
if([string]::IsNullOrEmpty($Error){
"$(Get-Date -f 'yyyy-MM-dd hh:mm:ss') $extractFile" | Out-File "c:\temp\mylogfile.txt" -Append
}else{
"$(Get-Date -f 'yyyy-MM-dd hh:mm:ss') $Error" | Out-File "c:\temp\mylogfile.txt" -Append
}
}
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.