2

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#?

6
  • In general, when working in PowerShell, I take the position that inline-C# should be used only as a last resort, if there is no other sensible way of accomplishing the desired aim. Commented Apr 21, 2017 at 13:12
  • @JeffZeitlin Could you explain why you take that stance? Commented Apr 21, 2017 at 13:14
  • I don't see any problem with this. I do it with my PS scripts that use XAML for UI's. Just keep it clean. Commented Apr 21, 2017 at 13:17
  • Sorry, but could not catch your idea. In PS 5.0 you can construct your own classes. Just search for PowerShell Class. Commented Apr 21, 2017 at 13:18
  • @autosvet I am aware that PS5 is awesome, but my question was in regards to PS3 and earlier (see tag, and where I specifically mentioned "before PSv5 came along" Commented Apr 21, 2017 at 13:19

1 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.