Getting started with PowerShellLoopsOperatorsUsing ShouldProcessPowerShell ClassesSwitch statementWorking with ObjectsUsing existing static classesBasic Set OperationsPowerShell FunctionsSending EmailHandling Secrets and CredentialsPowershell RemotingPowerShell "Streams"; Debug, Verbose, Warning, Error, Output and InformationVariables in PowerShellCommunicating with RESTful APIsWorking with the PowerShell pipelinePowerShell Background JobsReturn behavior in PowerShellWorking with XML FilesIntroduction to PsakeUsing the progress barStringsTCP Communication with PowerShellSharePoint ModuleAliasesAutomatic VariablesEnvironment VariablesPowershell profilesEnforcing script prerequisitesUsing the Help SystemSplattingDesired State ConfigurationSigning ScriptsSecurity and CryptographyCSV parsingIntroduction to PesterModules, Scripts and FunctionsPowerShell.exe Command-LineCommon parametersParameter setsRegular ExpressionsPowerShell Dynamic ParametersWMI and CIMGUI in PowershellConditional logicURL Encode/DecodeMongoDBRunning ExecutablesError handlingHashTablesActiveDirectory modulepowershell sql queriesAutomatic Variables - part 2Package managementCmdlet NamingBuilt-in variablesCreating DSC Class-Based ResourcesPowershell ModulesPowerShell WorkflowsHow to download latest artifact from Artifactory using Powershell script (v2.0 or below)?Calculated PropertiesSpecial OperatorsAnonymize IP (v4 and v6) in text file with PowershellComment-based helpAmazon Web Services (AWS) Simple Storage Service (S3)Amazon Web Services (AWS) RekognitionPSScriptAnalyzer - PowerShell Script AnalyzerNaming ConventionsEmbedding Managed Code (C# | VB)Archive ModuleInfrastructure AutomationScheduled tasks moduleISE module

Embedding Managed Code (C# | VB)

Other topics

Remarks:

Removing Added types

In later versions of PowerShell, Remove-TypeData has been added to the PowerShell cmdlet libraries which can allow for removal of a type within a session. For more details on this cmdlet, go here: https://msdn.microsoft.com/en-us/powershell/reference/4.0/microsoft.powershell.utility/remove-typedata

CSharp and .NET syntax

For those experience with .NET it goes without saying that the differing versions of C# can be quite radically different in their level of support for certain syntax.

If utilising Powershell 1.0 and/or -Language CSharp, the managed code will be utilising .NET 2.0 which is lacking in a number of features which C# developers typically use without a second thought these days, such as Generics, Linq and Lambda. On top of this is formal polymorphism, which is handled with defaulted parameters in later versions of C#/.NET.

C# Example

This example shows how to embed some basic C# into a PowerShell script, add it to the runspace/session and utilise the code within PowerShell syntax.

$code = "
using System;

namespace MyNameSpace
{
    public class Responder
    {
        public static void StaticRespond()
        {
            Console.WriteLine("Static Response");
        }

        public void Respond()
        {
            Console.WriteLine("Instance Respond");
        }
    }
}
"@

# Check the type has not been previously added within the session, otherwise an exception is raised
if (-not ([System.Management.Automation.PSTypeName]'MyNameSpace.Responder').Type)
{
    Add-Type -TypeDefinition $code -Language CSharp;
}

[MyNameSpace.Responder]::StaticRespond();

$instance = New-Object MyNameSpace.Responder;
$instance.Respond();

VB.NET Example

This example shows how to embed some basic C# into a PowerShell script, add it to the runspace/session and utilise the code within PowerShell syntax.

$code = @"
Imports System

Namespace MyNameSpace
    Public Class Responder
        Public Shared Sub StaticRespond()
            Console.WriteLine("Static Response")
        End Sub

        Public Sub Respond()
            Console.WriteLine("Instance Respond")
        End Sub
    End Class
End Namespace
"@

# Check the type has not been previously added within the session, otherwise an exception is raised
if (-not ([System.Management.Automation.PSTypeName]'MyNameSpace.Responder').Type)
{
    Add-Type -TypeDefinition $code -Language VisualBasic;
}

[MyNameSpace.Responder]::StaticRespond();

$instance = New-Object MyNameSpace.Responder;
$instance.Respond();

Parameters:

ParameterDetails
-TypeDefinition<String_>Accepts the code as a string
-Language<String_>Specifies the Managed Code language.Accepted values: CSharp, CSharpVersion3, CSharpVersion2, VisualBasic, JScript

Contributors

Topic Id: 9823

Example Ids: 30242,30243

This site is not affiliated with any of the contributors.