C# と VB.NET を使用して SSIS 2012 で記述されたサンプル パッケージ
これは、SSIS 2012 で記述された、スクリプト タスクを使用して探していることを実行するサンプル パッケージです。SSIS を使用する必要はありません。単純な C# または VB.NET コンソール アプリケーションを使用してこれを行うこともできますが、SSIS を使用すると、情報をログに記録してジョブをスケジュールする柔軟性が得られます。
フォルダ構成(初期)
フォルダが次のように構成されているとします。
コピーしたいソースファイルがあります。
Source
    |- Sample_File.txt
ターゲットのフォルダー構造は次のとおりです。
Target
    |- Target_1
    |    |- Archive
    |    |- Sample_File.txt
    |- Target_2
    |- Target_3
        |- Sample_File.txt
SSIS パッケージを作成し、フォルダー変数を作成します。
Variable name       Data type  Value
------------------ ---------- ----------------------
Backup_FolderName  String      Archive
Source_FileName    String      Sample_File.txt
Source_FilePath    String
Source_Folder      String      D:\SSIS\Files\Source\
Target_Folder      String      D:\SSIS\Files\Target\
変数Source_FilePathを選択し、 をクリックF4してプロパティを表示します。プロパティEvaluateAsExpressionを true に変更します。プロパティの横にある省略記号ボタンをクリックして、式ビルダーExpressionを開きます。式を に設定します。@[User::Source_Folder] + "\\" +  @[User::Source_FileName]
ソース ファイル パスを格納する変数を 1 つだけ持つことができます。私は通常、ソース フォルダーとファイル名を分けておくことを好みます。
スクリプト タスクを制御フロー タブにドラッグ アンド ドロップします。スクリプト タスクをダブルクリックして、スクリプト タスク エディターを開きます。スクリプト タブ ページで、横にある省略記号ボタンをクリックしReadOnlyVariables、次の変数を選択します。これらの変数はスクリプト タスク コードで使用するためです。
User::Source_FilePath
User::Target_Folder
User::Backup_FolderName
[スクリプトの編集... ] ボタンをクリックし、以下に示すようにコードを入力します。
SSIS 2008 以降の C# のみのスクリプト タスク コード:
スクリプト タスク コードは次のことを行います。
ソースファイルのパスが有効かどうかをチェックします。無効な場合は、メッセージをスローしてプロセスを終了します。
 
ターゲット フォルダが有効かどうかを確認します。無効な場合は、メッセージをスローしてプロセスを終了します。
 
ソース ファイル パスとターゲット フォルダーが有効な場合、ロジックは、ターゲット フォルダー内のサブフォルダー内のソース ファイル名の一致するすべての場所をループします。一致するファイルがある場合、ターゲット ファイルをバックアップ フォルダにコピーし、ターゲット ファイルをソース ファイルで上書きします。
 
スクリプト タスクは適切な情報を出力するため、SSIS 2012 の SQL Server Data Tools (SSDT) または SSIS 2005 - SSIS 2008 R2 の Business Intelligence Development Studio (BIDS) の進行状況/実行結果タブ内でステータスを追跡できます。
地域の名前空間
システムを使用する; System.Data の使用; Microsoft.SqlServer.Dts.Runtime を使用します。System.Windows.Forms を使用します。System.IO の使用;
エンドリージョン
名前空間 ST_523853dfbc0d4123be43383671f8a6c6 { [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute] public 部分クラス ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase { public void Main() { try { bool fireAgain = false; string backupFolder = string.Empty; string backupFilePath = string.Empty;
            string sourcFilePath = Dts.Variables["User::Source_FilePath"].Value.ToString();
            string targetFolder = Dts.Variables["User::Target_Folder"].Value.ToString();
            string backupFolderName = Dts.Variables["User::Backup_FolderName"].Value.ToString();
            if (String.IsNullOrEmpty(sourcFilePath) || !File.Exists(sourcFilePath))
            {
                // Check if a valid source file path was specified on the package variable
                Dts.Events.FireError(101, "Source path error", String.Format("You need to set a valid source file path in the package variable 'Source_FilePath'. Invalid path: '{0}'", sourcFilePath), string.Empty, 0);
                Dts.TaskResult = (int)ScriptResults.Failure;
            }
            else if (String.IsNullOrEmpty(targetFolder) || !Directory.Exists(targetFolder))
            {
                // Check if a valid target folder was specified on the package variable
                Dts.Events.FireError(102, "Target folder error", String.Format("You need to set a valid target folder location in the package variable 'Target_Folder'. Invalid folder: '{0}'", targetFolder), string.Empty, 0);
                Dts.TaskResult = (int)ScriptResults.Failure;
            }
            else
            {
                FileInfo sourceInfo = new FileInfo(sourcFilePath);
                // Loop through each file that matches the name of the source file
                foreach (string targetFilePath in Directory.EnumerateFiles(targetFolder, sourceInfo.Name, SearchOption.AllDirectories))
                {
                    FileInfo targetInfo = new FileInfo(targetFilePath);
                    backupFolder = Path.Combine(targetInfo.Directory.FullName, backupFolderName);
                    backupFilePath = Path.Combine(backupFolder, backupFolderName);
                    // If the backup folder does not exist in the folder within root target folder, create the backup folder.
                    if (!Directory.Exists(backupFolder))
                    {
                        Directory.CreateDirectory(backupFolder);
                        Dts.Events.FireInformation(401, "Backup folder created", String.Format("Backup folder '{0}' was created.", backupFolder), string.Empty, 0, ref fireAgain);
                    }
                    // Archive the target file to the backup folder.
                    File.Copy(targetFilePath, backupFilePath, true);
                    Dts.Events.FireInformation(402, "Target file archived", String.Format("Target file '{0}' was archived to the backup folder '{1}'.", targetFilePath, backupFolder), string.Empty, 0, ref fireAgain);
                    // Overwrite the target file with the source file.
                    File.Copy(sourcFilePath, targetFilePath, true);
                    Dts.Events.FireInformation(403, "Target file overwritten", String.Format("Target file '{0}' was overwritten with the source file '{1}'.", sourcFilePath, targetFilePath), string.Empty, 0, ref fireAgain);
                }
                Dts.TaskResult = (int)ScriptResults.Success;
            }
        }
        catch (Exception ex)
        {
            Dts.Events.FireError(100, "Unhandled exception", ex.ToString(), string.Empty, 0);
        }
    }
    #region ScriptResults declaration
    enum ScriptResults
    {
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    };
    #endregion
}
}
 
SSIS 2005 以降の VB.NET のスクリプト タスク コード:
#Region "Imports"
Imports System
Imports System.Data
Imports System.Math
Imports System.IO
Imports Microsoft.SqlServer.Dts.Runtime
#End Region
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
    Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    Public Sub Main()
        Try
            Dim fireAgain As Boolean = False
            Dim backupFolder As String = String.Empty
            Dim backupFilePath As String = String.Empty
            Dim sourcFilePath As String = Dts.Variables("User::Source_FilePath").Value.ToString()
            Dim targetFolder As String = Dts.Variables("User::Target_Folder").Value.ToString()
            Dim backupFolderName As String = Dts.Variables("User::Backup_FolderName").Value.ToString()
            If String.IsNullOrEmpty(sourcFilePath) OrElse Not File.Exists(sourcFilePath) Then
                ' Check if a valid source file path was specified on the package variable
                Dts.Events.FireError(101, "Source path error", String.Format("You need to set a valid source file path in the package variable 'Source_FilePath'. Invalid path: '{0}'", sourcFilePath), String.Empty, 0)
                Dts.TaskResult = ScriptResults.Failure
            ElseIf String.IsNullOrEmpty(targetFolder) OrElse Not Directory.Exists(targetFolder) Then
                ' Check if a valid target folder was specified on the package variable
                Dts.Events.FireError(102, "Target folder error", String.Format("You need to set a valid target folder location in the package variable 'Target_Folder'. Invalid folder: '{0}'", targetFolder), String.Empty, 0)
                Dts.TaskResult = ScriptResults.Failure
            Else
                Dim sourceInfo As FileInfo = New FileInfo(sourcFilePath)
                ' Loop through each file that matches the name of the source file
                For Each targetFilePath As String In Directory.EnumerateFiles(targetFolder, sourceInfo.Name, SearchOption.AllDirectories)
                    Dim targetInfo As FileInfo = New FileInfo(targetFilePath)
                    backupFolder = Path.Combine(targetInfo.Directory.FullName, backupFolderName)
                    backupFilePath = Path.Combine(backupFolder, backupFolderName)
                    ' If the backup folder does not exist in the folder within root target folder, create the backup folder.
                    If Not Directory.Exists(backupFolder) Then
                        Directory.CreateDirectory(backupFolder)
                        Dts.Events.FireInformation(401, "Backup folder created", String.Format("Backup folder '{0}' was created.", backupFolder), String.Empty, 0, fireAgain)
                    End If
                    ' Archive the target file to the backup folder.
                    File.Copy(targetFilePath, backupFilePath, True)
                    Dts.Events.FireInformation(402, "Target file archived", String.Format("Target file '{0}' was archived to the backup folder '{1}'.", targetFilePath, backupFolder), String.Empty, 0, fireAgain)
                    ' Overwrite the target file with the source file.
                    File.Copy(sourcFilePath, targetFilePath, True)
                    Dts.Events.FireInformation(403, "Target file overwritten", String.Format("Target file '{0}' was overwritten with the source file '{1}'.", sourcFilePath, targetFilePath), String.Empty, 0, fireAgain)
                Next
                Dts.TaskResult = ScriptResults.Success
            End If
        Catch ex As Exception
            Dts.Events.FireError(100, "Unhandled exception", ex.ToString(), String.Empty, 0)
            Dts.TaskResult = ScriptResults.Failure
        End Try
    End Sub
#Region "ScriptResults declaration"
    Enum ScriptResults
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum
#End Region
End Class
無効なソース ファイル パスが指定された場合、パッケージは次のエラー メッセージをスローします。

無効なターゲット フォルダーが指定されている場合、パッケージは次のエラー メッセージをスローします。

ソースとターゲットの場所が有効な場合、パッケージは正常に実行されます。この例では、
- の下
Target_1にバックアップ フォルダがあったため、フォルダは作成されませんでしたが、ファイルはバックアップ フォルダにコピーされました。 
- に一致するファイルがなかった
Target_2ため、アクションは実行されませんでした。 
- でバックアップ フォルダが作成されまし
Target_3た。ファイルはターゲットの場所にコピーされ、ソース ファイルで上書きされました。 

フォルダ構成(最終)
パッケージの実行後、ターゲットの場所は次のようになります。
Target
    |- Target_1
    |    |- Archive
    |        |- Sample_File.txt
    |    |- Sample_File.txt
    |- Target_2
    |- Target_3
        |- Archive
            |- Sample_File.txt
        |- Sample_File.txt