Search code examples
c#powershellpowershell-3.0

When to Use C# in a PowerShell Script | PSObject


Are there certain situations where a admin would want to stay away from writing C# into a PowerShell Script?

For example, I like to have my PowerShell scripts configurable from xml control files. But then creating tasks based on these control files is daunting because it is hard to create robust objects in PowerShell which are capable of holding data structures I like. There are methods such as:

$myObject = New-Object -TypeName PSObject

But I find that I am often left wishing I could have arrays, hashtables, etc. kept inside these objects. And the easiest way to do so would be to create a C# constructor -- since I do not know of a way to keep a hashtable inside a PSObject property.

Add-Type -Language CSharp @"
public class myObject{
    public String myString;
    public hashtable myHash;
}

1.) Is it 'OKAY' to use C# commonly in PowerShell for this reason? Is this what everyone did before PSv5 came along and introduced Class constructs?

2.) Is there additional upkeep that should be done to maintain the C# code?

Ex.) I upgrade from server 2012 to 2016 -- keeping powershell scripts. I know the powershell is forward compatible, but what about the C#?


Solution

  • Nothing speaks against using C# within PowerShell from a technical perspective. However, I would try to avoid it since this will make your script harder to read and maintain.

    In your example, you could write a function that creates the object for you:

    function New-MyObject
    {
        [CmdletBinding()]
        Param
        (
            [Parameter(Mandatory=$true)]
            [string]$myString,
    
            [Parameter(Mandatory=$true)]
            [hashtable]$myHash
        )
    
        [PSCustomObject]@{
            MyString = $myString
            MyHash = $myHash
        }
    }