Using PowerShell to copy SQDR CSV files to Azure Storage
Copyright 2021 StarQuest Ventures, Inc. 
12/1/21

Attached PowerShell example scripts:

# This script performs the following tasks:
#   Pause an I/R destination
#   Copy CSV tables to an intermediate directory
#   Clear the contents of the active CSV tables
#   Resume the I/R group
#   For each CSV file in the intermediate directory:
#     If the file is empty (i.e. there were no changes), ignore it
#     Rename the file to <table><timestamp>.CSV
#     copy the CSV file to Azure Data Lake Storage gen2
#     If there is a problem copying to ADLSg2, move the file to a holding directory

* parms.ps1 - first edit this file to customize parameters for your environment.
Customization information is documented as comments.

* setup_azure.ps1 - this should be run once to verify connectivity and to create the Azure container and directory. 
The directory can also be autocreated when you start uploading CSV files.

* sqdr_azure.ps1 - this script should tested (run it from an elevated PowerShell command window for foreground testing), and then deployed as a Windows scheduled task. 

* sqdr_azure.cmd - customize and run this as a scheduled task.  This handles the creation of log files.  
#   On the General tab, use Change User or Group... to specify the user account to run the task. Typically you will use SYSTEM (Local system account). 
#   Also select "Run whether user is logged on or not"
#   On the Actions tab, select New... and browse to the location of sqdr_azure.cmd
#   On the Triggers tab, select New... and configure when to run the task.

You should also add a nightly or weekly scheduled task to clean up the log files.

Create local Windows directories as needed for 
 SrcDirectory - where SQDR is writing the CSV files
 WorkDir - intermediate directory
 holdDir - the directory to save CSV files that were not successfully uploaded to Azure Storage


PREREQUISITES:

* PowerShell version 5.1 or higher. This is included as part of Windows Server 2016 later. If you are using Windows Server 2012r2, you can download PowerShell 5.1 from Microsoft.

The following command displays the version of PowerShell

echo $PSVersionTable.PSVersion.ToString()

* .NET Framework is 4.7.2 or greater installed.  Windows Server 2019 & 2022 already meet this requirement; for Windows Server 2016 & earlier, you can download from

https://dotnet.microsoft.com/download/dotnet-framework

The latest version is 4.8 (recommended), and we recommend running Windows Update after installing to get the latest cumulative update.

To determine the installed version of .NET Framework, examine the registry at 
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full. 

Or use the PowerShell command:
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"

Version       : 4.7.03062 is 4.7.2


* Install Az.Storage module:

Install-Module Az.Storage -Repository PSGallery -Force  

On Windows 2016, you may need to issue these commands first:
Ensure we are using TLS 1.2:
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
 
Install NuGet first:
Install-PackageProvider -Name NuGet -Force

Install-Module Az.Storage -Repository PSGallery -Force  

* An Azure subscription. 

* A storage account that has hierarchical namespace enabled.

The following Azure information is needed:

* storage_account name
* storage account key
* Name of the Container and directory that you wish to use - this can be created by the setup_azure script (assuming you have authority to do so).


USAGE
=====

Expand the zip file into a directory e.g. C:\Scripts

Edit the accompanying parms.ps1 e.g. file locations of the active CSV files and the transfer folder, name of the I/R group or destination, etc 
Also edit the DIR property within the script if you are using a directory other than C:\Scripts

Create a scheduled task.  For Actions, choose "Start a program", enter "powershell" for the program/script, and enter 
   -F C:\scripts\sqdr_azure.ps1 for the arguments.

Or (recommended) use sqdr_azure.cmd so you can redirect output to a log file.  
If you do this, also create a nightly or weekly scheduled task to rotate the log files.

On the General tab, use Change User or Group... to specify the user account to run the task. Typically you will use SYSTEM (Local system account). 
Also select "Run whether user is logged on or not"

# To run from a command window, start PowerShell as Administrator

Troubleshooting:
================

* If you get an error "Powershell script not digitally signed", unblock the PS1 file.

* If you get an authority error when the script is pausing the incremental destination or group, verify
that you are running from an elevated PowerShell command window (logged on as a user with local admin rights),
or that the scheduled task is running as such a user - we recommend using SYSTEM for the scheduled task.


IN SQDR (Data Replicator Manager):
==================================

* Create the CSV destination using an ODBC connection string or an ODBC data source

SQDR creates the CSV files using the "SQDR Text" ODBC driver with a connection string that looks like
Database=C:\Scripts\Transfer;TableType=Character;Delimiter=|;DataFileExtension=CSV;FirstLineNames=1

Other possible options:
 If you do not specify FirstLineNames=1, set $FirstLineNames="0" in parms.ps1

 AllowUpdateAndDelete=1 is not needed if the I/R group (or all subscriptions) is configured for Archive All DML Activity
  However, it is needed if you want saving the subscription to recreate the CSV file (e.g. to add columns)

 Database=C:\Scripts\Transfer;AllowUpdateAndDelete=1;TableType=Character;Delimiter=|;DataFileExtension=CSV;FirstLineNames=1



* Create I/R group

* On Advanced panel, set Subscription Wizard Defaults to:
Archive all DML Activity

* Create the subs using Insert Member under the I/R group/Members

* On the destination panel:

-- The Destination DDL Options on the Destination panel should be set to 
Create (table) if does not exist; else use existing

-- Baseline Replication Options should be
Append replicated rows to existing data

-- If you only want incremental changes and not baselines, then set 
Null synchronization - DDL only

* When creating the sub, add desired derived columns e.g. 
@TYPE VARCHAR(1)
@TX  VARCHAR(20)
@SEQ  VARCHAR(20)

Note that these columns will be blank for a baseline (so they should be nullable); they only have values for incremental changes.


Areas for improvements:
======================

* Azure Authorization
The script assumes we are using a storage account key for authorization.
See New-AzStorageContext for other options such as Azure Active Directory
https://docs.microsoft.com/en-us/powershell/module/az.storage/new-azstoragecontext?view=azps-6.6.0

* filtering on the files (if desired)

* handle a marker table (indicating end of day processing)

* This script uses New-AzDataLakeGen2Item to copy the CSV files one at a time.  Look into the azcopy command which supports wildcard copy.

* Improve error checking. This is especially important for the operation writing to Azure, since if that fails, we have no recovery if we don't save a copy of the file.

Here is the current state of error handling:

- If you supply an incorrect name for the storage account, the script hangs forever (or perhaps I didn't wait long enough)
There may be some way to specify a timeout.

- If you supply incorrect credentials for the storage account, you get this error:
New-AzDataLakeGen2Item : Server failed to authenticate the request. Make sure the value of Authorization header is
formed correctly including the signature. HTTP Status Code: 403 - HTTP Error Message: Server failed to authenticate
the request. Make sure the value of Authorization header is formed correctly including the signature.
ErrorCode: AuthenticationFailed

- If the container does not exist, you get this error
New-AzDataLakeGen2Item : The specified container does not exist. HTTP Status Code: 404 - HTTP Error Message: The specified container does not exist.
ErrorCode: ContainerNotFound

- If the directory does not already exists, it is automatically created if you are authorized to do so.

- If the destination file already exists, it is overwritten.  This situation seems unlikely since we are appending a timestamp (including milliseconds) to the filename.

Removing the -force option will cause this message when run as a foreground job; if invoked as a scheduled task - it may hang forever.

Are you sure to overwrite 'https://adlsg2sq.blob.core.windows.net/sqdr/sqdrdirx/x.ps1'?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"):


* Designing for long running jobs:
If there is a possibility that the script may take a while to run
- i.e. if another invocation of the script may occur before the current run completes
and you may have more than one invocation of the script running at the same time
Then the name of this directory should be something unique like a timestamp with hour

Note that additional cleanup will be necessary to delete that directory once the script completes
Also will need to have multiple Azure transfer log files and handle cleanup for those
I would suggest letting the Azure transfer log files accumulate for a day and use a nightly scheduled task to remove them
$WorkDir = Get-Date -Format "yyyyMMddhh"


REFERENCES:

 https://docs.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-directory-file-acl-powershell
Use PowerShell to manage directories and files in Azure Data Lake Storage Gen2

