Suppose I have a SQL Table that has these columns:
[server_name],[SESSION_ID],[SESSION_SPID]I am trying to copy values stored in a data table (
$dmvResult) to the SQL Table above ($Table)
$dmvResult = DMV_Query 'SELECT [SESSION_ID] ,[SESSION_SPID] FROM $SYSTEM.DISCOVER_SESSIONS';
$ConnectionString =‘Data Source=$server; Database=$database; Trusted_Connection=True;’
$bulkCopy = new-object Data.SqlClient.SqlBulkCopy($ConnectionString)
$bulkCopy.DestinationTableName=$Table
$bulkCopy.WriteToServer($dmvResult)
While the copying is being done successfully, there is an issue: it’s copying by position, not by column name match. In other words, the copied columns are not being mapped and copied to the same columns.
[SESSION_ID] is being copied to [server_name] and [SESSION_SPID] is being copied to [SESSION_ID]
How can I tell bulkCopy to match columns and copy?
The result copy should be [server_name] being empty because it wasn’t selected from DMV query.
I found a neat solution in this thread:
https://stackoverflow.com/a/20045505/8397835
but I dont know how to translate it to my powershell code:
var meta = definition.Context.Mapping.GetMetaType(typeof(T));
foreach (var col in meta.DataMembers)
{
copy.ColumnMappings.Add(col.Member.Name, col.MappedName);
}