将PowerShell控制台文本写入文件



我有一个PowerShell脚本,它连接到数据库并在一些数据上循环。

脚本完成或抛出错误后,我需要将控制台中显示的任何文本附加到日志文件中。

我无法使用Write-Output实现这一点,因为我不想保存特定的值,我只需要将整个控制台文本附加到一个文件中。

谢谢。

编辑:

事实上,我正在寻找的最终结果是一个带有时间戳的日志文件,这是我的代码:

$server = "USERSQLEXPRESS"
$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):csvfiles"
# 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(的文件名和时间戳,然后如果发生错误,我也需要打印时间戳,以此类推,直到脚本完成。

您可以使用Start-Transcripttry/catch/finally或编写自己的代码(将控制台输出存储到变量中,并在需要时附加一个包含内容的文本文件(来执行此操作。注意-Append参数与Start-Transcript

如果没有代码,很难知道该推荐哪一个。

已展开

现在您已经添加了一些代码,请查看有关每个方法的一些附加信息。我不熟悉通过PowerShell的SQL,所以不确定你会得到什么样的输出/错误(关于错误,特别是是否存在终止或非终止(

转录本

Start-Transcript应该在开头,Stop-Transcript应该在结尾。这将记录控制台上正常显示的内容。在已经录制成绩单的情况下运行Start-Transcript将导致严重错误。

Start-Transcript -Path "ctempmylogfile.txt"
$server = "USERSQLEXPRESS"
$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

终止错误

视情况添加try/catch/finally。您可以懒惰地将其添加到整个代码中,或者正确地执行此操作并包装可能导致终止错误的部分。

...
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:tempmylogfile.txt" -Append
}else{
"$(Get-Date -f 'yyyy-MM-dd hh:mm:ss') $extractFile" | Out-File "c:tempmylogfile.txt" -Append
}
}
}
...

无终止错误

只需添加一行即可导出错误。确保清除每个环路的自动变量$Error

...
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:tempmylogfile.txt" -Append
}else{
"$(Get-Date -f 'yyyy-MM-dd hh:mm:ss') $Error" | Out-File "c:tempmylogfile.txt" -Append
}
}
...

您可以使用Start-Transcript进行调试:

Start-Transcript -path "C:tempmyTranscript.txt"

在脚本开始时添加,并将所有控制台输出写入C:tempmyTranscript.txt

最新更新