将写入Powershell错误消息写入SSIS

时间:2014-05-23 13:45:17

标签: powershell ssis

我有一个SSIS执行流程任务,我在调用PowerShell脚本。我发现如果PowerShell脚本失败,我可以通过捕获这样的错误来使进程任务失败:

trap {
  $err = $_.Exception
  while ( $err.InnerException )
  {
    $err = $err.InnerException
    Write-Host $err.Message
  };
  exit 1
}

我想收到错误消息以返回SSIS,但我似乎无法让它工作。它只返回以下内容:

  

流程退出代码为" 1"而预期的是" 0"。

感谢任何帮助。

完整代码:

Param(
 [String]$excelPath,
 [String]$serverName,
 [String]$databaseName,
 [String]$tableName
 )

$ErrorActionPreference = 'Stop'

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO.SqlDataType') | Out-Null

Trap {
  $err = $_.Exception
  while ( $err.InnerException )
    {
    $err = $err.InnerException
    Write-Host $err.Message
    };
    exit 1
  }

$excel = New-Object -ComObject excel.application 
$excel.visible = $False 
$excel.displayalerts=$False 
$workbook = $excel.Workbooks.Open($ExcelPath) 
$workSheet = $workbook.worksheets.Item(1).name 
$workbook.Close()
$excel.quit() 
$excel = $null

$query = "select * from [$workSheet`$]";

$connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$excelPath`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";"

# Instantiate some objects which will be needed
$serverSMO = New-Object Microsoft.SqlServer.Management.Smo.Server($serverName)
$db = $serverSMO.Databases[$databaseName];

$newTable = New-Object Microsoft.SqlServer.Management.Smo.Table ;
$newTable.Parent = $db;
$newTable.Name = $tableName ;

$conn = New-Object System.Data.OleDb.OleDbConnection($connectionString)
$conn.open()


$cmd = New-Object System.Data.OleDb.OleDbCommand($query,$conn) 
$dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter($cmd) 
$dataTable = New-Object System.Data.DataTable 

$dataAdapter.fill($dataTable)
$conn.close()

# Drop the table if it exists
if($db.Tables.Contains($tableName).Equals($true))
{
    ($db.Tables[$tableName]).Drop()
}

# Iterate the columns in the DataTable object and add dynamically named columns to the SqlServer Table object.
foreach($col in $dataTable.Columns)
    {
    $sqlDataType = [Microsoft.SqlServer.Management.Smo.SqlDataType]::Varchar
    $dataType = New-Object Microsoft.SqlServer.Management.Smo.DataType($sqlDataType);
    $dataType.MaximumLength = 1000;
    $newColumn = New-Object Microsoft.SqlServer.Management.Smo.Column($newTable,$col.ColumnName,$dataType);
    $newColumn.DataType = $dataType;
    $newTable.Columns.Add($newColumn);
}
$newTable.Create();

#bcp data into new table
$connectionString = "Data Source=$serverName;Integrated Security=true;Initial Catalog=$databaseName;"
$bc = New-Object ("Data.SqlClient.SqlBulkCopy") $connectionString
$bc.DestinationTableName = "$tableName"
$bc.WriteToServer($dataTable)

0 个答案:

没有答案