Calling Static Methods from Powershell with an Out Parameter

It's fairly common in .NET to have methods with a "ref" or "out" keyword on one of the parameters. This often brings up the question: How do you call such a method from PowerShell? Fortunately, PowerShell makes this relatively simple.

The first step is understanding how to call a static .NET method from PowerShell. Let's say you have a class called "Motorcycle" like below:

                                        
  public class Motorcycle
  {
    public Motorcycle() { }

    /// 
    /// Returns a List of all Motorcycles from the database
    /// 
    /// 
    public static List GetAllMotorcycles()
    {
        List mList = new List();
        // TODO: Retrieve objects from the database
        return mList;
    }

    /// 
    /// Gets a Motorcycle with a specific ID
    /// 
    /// 
    public static void FindMotorcycleByID(out Motorcycle cycle, int cycleID)
    {
        // Load from the database
        cycle = RetrieveCycle(cycleID);
    }
  }

                                        

Assuming your assembly is loaded you can call the static "GetAllMotorcycles" method with the following PowerShell code:

                                        
  [CycleProject.Motorcycle]::GetAllMotorcycles()

                                        

Next, lets take a look at how you would call "FindMotorcycleByID" which uses an "out" parameter. You first need to define a variable called $cycle of type "Motorcycle" that will get the value back from the method. Lastly, specify this variable in the method call:

                                        
  # Define a Motorcycle Variable
  $cycle = New-Object -TypeName CycleProject.Motorcycle
      
  # Variable for the Motorcycle ID we want to find
  $motocycleID = 46

  # Call FindMotorcycleById
  [CycleProject.Motorcycle]::FindMotorcycleById([ref] $cycle,$motocycleID)

                                        

You might have noticed that [ref] was used for the "out" parameter. This is because PowerShell uses "[ref]" regardless of if the method specifies "out" or "ref". As you can see PowerShell makes it easy to call static methods and integrate .NET objects into your scripts.

Bonus Tip: You can load an assembly into a PowerShell session with the Add-Type cmdlet.

  # Load the CycleProject assembly
  Add-Type -Path "G:\Assemblies\CycleProject.dll"

                                        


© 2024 Embrs.net