dataplat / Invoke-SqlCmd2

PowerShell module containing Invoke-SqlCmd2
MIT License
66 stars 35 forks source link

`-As PSObject` does not work on PowerShell Core #33

Open Szeraax opened 1 year ago

Szeraax commented 1 year ago

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: $_"
    }
}
B-Art commented 1 month ago

Is this like difference between: if ($a -eq $null) {#} and if ($null -eq $a ) {#}