VB.NET Example

suggest change

This example embeds VB.NET in a PowerShell script with Add-Type -Language VisualBasic, then calls it from PowerShell. Add-Type types stay loaded for the session. The PSTypeName check avoids adding the same type twice. Console.WriteLine writes to the process console, not the PowerShell success stream.

$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();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents