RSS

Converting XML to PowerShell PSObject

Recently, I was working on some code (of course) and had a need to convert some XML to PowerShell PSObjects. I found some snippets out there that sort of did this, but not the way that I needed for this exercise. In this case I’m converting XML meta data from Plex.


function ConvertFrom-XmlPart($xml)
{
    $hash = @{}
    $xml | Get-Member -MemberType Property | `
        % {
            $name = $_.Name
            if ($_.Definition.StartsWith("string ")) {
                $hash.($Name) = $xml.$($Name)
            } elseif ($_.Definition.StartsWith("System.Object[] ")) {
                $obj = $xml.$($Name)
                $hash.($Name) = $($obj | %{ $_.tag }) -join "; "
            } elseif ($_.Definition.StartsWith("System.Xml")) {
                $obj = $xml.$($Name)
                $hash.($Name) = @{}
                if ($obj.HasAttributes) {
                    $attrName = $obj.Attributes | Select-Object -First 1 | % { $_.Name }
                    if ($attrName -eq "tag") {
                        $hash.($Name) = $($obj | % { $_.tag }) -join "; "
                    } else {
                        $hash.($Name) = ConvertFrom-XmlPart $obj
                    }
                }
                if ($obj.HasChildNodes) {
                    $obj.ChildNodes | % { $hash.($Name).($_.Name) = ConvertFrom-XmlPart $($obj.$($_.Name)) }
                }
            }
        }
    return $hash
}

function ConvertFrom-Xml($xml) 
{
    $hash = @{}
    $hash = ConvertFrom-XmlPart($xml)
    return New-Object PSObject -Property $hash
}

 
Leave a comment

Posted by on June 5, 2015 in Uncategorized

 

Tags: ,

Converting an ADO RecordSet from an SP into a Powershell Object result set

Recently I was creating a Powershell script to perform some unit tests on some old COM+ objects that we needed to make some minor tweaks to. One of the methods in the COM+ object executes a Stored Procedure returning a ADODB Recordset. Trying to pipe out the results of the method provided useless results. However, the Recordset does provide everything we need to create Powershell objects, and generate a Powershell result set.

I start out by defining a constant (adInteger) for the parameter ($test) that I’m going to pass to the stored procedure, then I call the method (RunSPReturnRS) on the COM+ object ($oDAL). Then I loop through the rows until EOF is true. For each row I create a new hash table ($hash). For each field I had the field’s value to the hash table using the field’s name as the label. Then I add these to the results array ($results).

if (!(Test-Path variable:global:adInteger)) { New-Variable -Name adInteger -Value 3 -Option Constant }
try
{
    $oDAL = New-Object -ComObject "DAL.dbaccessor"
    # Define the parameter(s) for the Stored Procedure
    $parm = @("@excludeUSA", $adInteger, 4, 0)
    # Create the results as an empty array
    $results = @()

    # Invoke the COM+ method
    $objRS = $oDAL.RunSPReturnRS("stp_GetCountries", "ConnectionString", "", [ref]$parm)
    
    # Loop through the result rows until EOF
    while ($objRS.EOF -ne $True) {
        # Create an empty hash array for the row contents
        $hash = @{}
        # Fill the hash array with the Field names and values
        $objRS.Fields | % { $hash.$($_.name) = $_.value }
        # Convert the hash array to a Powershell object and add it to the results
        $results += New-Object PSObject -property $hash
        $objRS.MoveNext()
    }
    $results | Format-Table -AutoSize
    $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($oDAL)
}
catch
{
    "`n{0}.{1} -- {2}`n`n{3}`n`n{4}" -f $_.Exception.Source, $_.FullyQualifiedErrorId, $_.Exception.CommandName, 
        $_.Exception.Message, $_.Exception.StackTrace
}

This ends up producing a nicely formatted table output of the results of the stored procedure.

 
Leave a comment

Posted by on May 1, 2015 in Uncategorized

 

Powershell, Jenkins, and repetitive tasks

The company I’m working for has been using Jenkins for a while now to automate the build process of our various code bases. However, Jenkins is capable of so much more with its embedded support for Powershell. We’ve recently started taking advantage of this by converting our Windows Scheduled Tasks and SQL Server Jobs to be hosted and managed within the our Jenkins process.

During this I’ve used several reference materials rather frequently and thought that I would share them with you.

Windows Powershell in Action, Second Action, Manning Publications Co.

Windows Powershell for Developers, O’Reilly Media

Hey, Scripting Guy! Blog

Remove-Module

This is an example of some of the documentation provided in the book Windows Powershell In Action, Second Action.

 
Leave a comment

Posted by on January 30, 2015 in Powershell

 

Tags: , , ,

Difference between int.Parse,Convert.ToInt32 and int.TryParse – CodeProject

Difference between int.Parse,Convert.ToInt32 and int.TryParse – CodeProject.

 
Leave a comment

Posted by on December 10, 2014 in .NET, C#, Uncategorized

 

Xamarin.Forms: What Developers Make of It — Visual Studio Magazine

Developer Feedback for Xamarin.Forms

Xamarin.Forms: What Developers Make of It — Visual Studio Magazine.

 
Leave a comment

Posted by on October 2, 2014 in Uncategorized

 

Simplifying Cross-Platform Mobile App Development with Xamarin.Forms — Visual Studio Magazine

Very light (quick read) article on Xamarin.Forms and Cross-Platform Mobile App Development Simplifying Cross-Platform Mobile App Development with Xamarin.Forms — Visual Studio Magazine.

 
Leave a comment

Posted by on October 2, 2014 in .NET, C#, Xamarin

 

Tags: , ,

What’s New in FOR XML in Microsoft SQL Server 2005

What's New in FOR XML in Microsoft SQL Server 2005.

 
Leave a comment

Posted by on June 11, 2014 in Uncategorized

 

Your Xamarin App in the Living Room with Amazon Fire TV | Xamarin Blog

Your Xamarin App in the Living Room with Amazon Fire TV | Xamarin Blog.

 
Leave a comment

Posted by on May 14, 2014 in Uncategorized

 

Get More Ratings for your Apps | Xamarin Blog

Get More Ratings for your Apps | Xamarin Blog.

 
Leave a comment

Posted by on May 14, 2014 in Uncategorized

 

Automatic Properties … Lazy coding or not?

Recently, I had a discussion with a fellow developer over the intent of automatic properties. While I understand the benefit of “less code”, I disagree with the concept on the principal that properties should be:

  1. Initialized
  2. Validated

I don’t believe that it is the responsibility of the class or the constructor to initialize or validate a property. .NET even goes so far as to provide an Attribute Class (DefaultValueAttribute Class) for the purpose of providing a default value.

I even found this useful snippet of code on stackoverflow (How To Initialize Autoproperty to not null) for initializing the properties from the “Default Values”:

static public void ApplyDefaultValues(object self)
{
    foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(self))
    {
        DefaultValueAttribute attr = prop.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;
        if (attr == null) continue;
        prop.SetValue(self, attr.Value);
    }
}
 
Leave a comment

Posted by on January 4, 2013 in .NET, C#, Managed