【发布时间】:2018-12-03 15:50:43
【问题描述】:
我有一个 PowerShell 脚本,它连接到数据库并循环访问一些数据。
脚本完成或引发错误后,我需要将控制台中显示的任何文本附加到日志文件中。
使用Write-Output 无法实现这一点,因为我不想保存特定值,我只需要将整个控制台文本附加到文件中。
谢谢。
编辑:
事实上,我正在寻找的最终结果是一个带有时间戳的日志文件,这是我的代码:
$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
}
我需要在日志文件中使用时间戳打印导出到 csv ($extractFile) 的每个文件名,然后如果发生错误,我也需要使用时间戳打印,依此类推,直到脚本完成。
【问题讨论】:
标签: powershell