Skip to content

-As PSObject does not work on PowerShell Core #33

@Szeraax

Description

@Szeraax

Core has different assemblies for scrubbing DBNull. Here is a fix by another person prior to invoking any Invoke-SqlCmd2 will cause the block in Invoke-SqlCmd2 to silently fail.

Src

# This code scrubs DBNulls.  Props to Dave Wyatt and fffnite
$cSharp = @'
    using System;
    using System.Data;
    using System.Management.Automation;

    public class DBNullScrubber
    {
        public static PSObject DataRowToPSObject(DataRow row)
        {
            PSObject psObject = new PSObject();

            if (row != null && (row.RowState & DataRowState.Detached) != DataRowState.Detached)
            {
                foreach (DataColumn column in row.Table.Columns)
                {
                    Object value = null;
                    if (!row.IsNull(column))
                    {
                        value = row[column];
                    }

                    psObject.Properties.Add(new PSNoteProperty(column.ColumnName, value));
                }
            }

            return psObject;
        }
    }
'@

try {
    if ($PSEdition -eq 'Core') {
        # Core doesn't auto-load these assemblies unlike desktop?
        # Not csharp coder, unsure why
        # by fffnite
        $Ref = @(
            'System.Data.Common'
            'System.Management.Automation'
            'System.ComponentModel.TypeConverter'
        )
    }
    else {
        $Ref = @(
            'System.Data'
            'System.Xml'
        )
    }
    Add-Type -TypeDefinition $cSharp -ReferencedAssemblies $Ref -ErrorAction stop
}
catch {
    If (-not $_.ToString() -like "*The type name 'DBNullScrubber' already exists*") {
        Write-Warning "Could not load DBNullScrubber.  Defaulting to DataRow output: $_"
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions