Home Blog Autogenerate PowerShell Functions from .NET Code
 

Autogenerate PowerShell Functions from .NET Code

Starting with version 2.0.12.6, ISESteroids has the capability to convert static .NET methods into PowerShell functions. Let's see what that is and why it could be useful.

Accessing Static .NET Methods

To access a static .NET method, not much is needed. You need the .NET type that is providing the methods, add two colons (::), and immediately, the ISE editors IntelliSense displays what's in that type.

Here are a couple of examples. The "Math" type helps with arithmetic operartions:

PS> [Math]::Min(2,6)
2

PS> 

  Getting the lower of two numbers

The "IO.Path" type assists with common path operations:

PS> [IO.Path]::ChangeExtension('c:\test.txt', 'bak')
c:\test.bak

PS>

  Changing the file extension of a path

And "Net.DNS" helps you query the DNS. This example finds the currently assigned IP address(es):

PS> [Net.DNS]::GetHostByName($env:COMPUTERNAME)

HostName                    Aliases                     AddressList              
––––––––                    –––––––                     –––––––––––              
tobi2                       {}                          {192.168.2.102}          

PS> 

  Getting the current IP address(es)

To find out more, send a .NET type off to Get-Member:

PS> [IO.Path] | Get–Member –Static

   TypeName: System.IO.Path

Name                        MemberType Definition                                
––––                        –––––––––– ––––––––––                                
ChangeExtension             Method     static string ChangeExtension(string pat…
Combine                     Method     static string Combine(string path1, stri…
Equals                      Method     static bool Equals(System.Object objA, S…
GetDirectoryName            Method     static string GetDirectoryName(string path)
GetExtension                Method     static string GetExtension(string path)   
GetFileName                 Method     static string GetFileName(string path)    
GetFileNameWithoutExtension Method     static string GetFileNameWithoutExtensio…
GetFullPath                 Method     static string GetFullPath(string path)    
GetInvalidFileNameChars     Method     static char[] GetInvalidFileNameChars()   
GetInvalidPathChars         Method     static char[] GetInvalidPathChars()       
GetPathRoot                 Method     static string GetPathRoot(string path)    
GetRandomFileName           Method     static string GetRandomFileName()         
GetTempFileName             Method     static string GetTempFileName()           
GetTempPath                 Method     static string GetTempPath()               
HasExtension                Method     static bool HasExtension(string path)     
IsPathRooted                Method     static bool IsPathRooted(string path)     
ReferenceEquals             Method     static bool ReferenceEquals(System.Objec…
AltDirectorySeparatorChar   Property   static char AltDirectorySeparatorChar {g…
DirectorySeparatorChar      Property   static char DirectorySeparatorChar {get;} 
InvalidPathChars            Property   static char[] InvalidPathChars {get;}     
PathSeparator               Property   static char PathSeparator {get;}          
VolumeSeparatorChar         Property   static char VolumeSeparatorChar {get;}    

  Listing static members of a type

Cmdlets are .NET

The results you get from .NET methods look surprisingly similar to what cmdlets output, and that's actually not that much of a surprise. Cmdlets are .NET code. And if you run ISESteroids, you can actually "see" this code.

Simply right-click any cmdlet, then in the enhanced context menu, choose "Source Code" and then "Decompile". You will be automatically taken to the relevant source code.

Funny enough, that also works with .NET methods like the ones you have just seen in the examples. So if you enter the examples into ISESteroids, and right-click for example "GetHostByName", then you can also look at the source code of these methods.

So the truth is: PowerShell is really working most of the time with .NET code. It is a thin wrapper around it, and cmdlets "civilize" .NET code and make it behave in a predictable and error-handled way.

Turning .NET Code into PowerShell

While you can happily use .NET code directly in your scripts (like shown in the examples before), it may sometimes be a better idea to wrap them into PowerShell functions. PowerShell functions really are cmdlets. They are just not binary, but otherwise provide the very same functionality and end-user experience.

This is when ISESteroids comes into play. It can do the work for you. Try this:

Enter the following code:

  


[Environment]::SetEnvironmentVariable(

  Pick a static .NET method…

The code above is pretty much what ISEs IntelliSense will type for you. Now to the magic part.

Right-click "SetEnvironmentVariable", and in the enhanced context menu, choose "Refactor", and then "Turn Method into Function". That's it. ISESteroids quickly generates the following for you:

  

<#
  Converting method "SetEnvironmentVariable" of type [System.Environment] to PowerShell
  2 overloads found.
  created 2 PowerShell functions.
  PowerShell code auto-created by ISESteroids 2.0 Enterprise
#>

# Overload #1:
function Set-EnvironmentVariable
{
  [CmdletBinding()]
  param
  (
    [Parameter(Mandatory=$true,ValueFromPipeline=$false)]
    [String]
    $variable,
   
    [Parameter(Mandatory=$true,ValueFromPipeline=$false)]
    [String]
    $value
   
  )
 
  process
  {
    try
    {
      [System.Environment]::SetEnvironmentVariable($variable, $value)
    }
    catch
    {
      Write-Warning "Error occured: $_"
    }
  }
}

# Overload #2:
function Set-EnvironmentVariable
{
  [CmdletBinding()]
  param
  (
    [Parameter(Mandatory=$true,ValueFromPipeline=$false)]
    [String]
    $variable,
   
    [Parameter(Mandatory=$true,ValueFromPipeline=$false)]
    [String]
    $value,
   
    [Parameter(Mandatory=$true,ValueFromPipeline=$false)]
    [EnvironmentVariableTarget]
    $target
   
  )
 
  process
  {
    try
    {
      [System.Environment]::SetEnvironmentVariable($variable, $value, $target)
    }
    catch
    {
      Write-Warning "Error occured: $_"
    }
  }
}

  …autogenerate fully error-handled and pipeline-aware PowerShell functions

Now the resulting functions work just like cmdlets. Simply run the script to define the functions.

Wrapping .NET code into PowerShell functions has a number of advantages. Aside from error handling and pipeline-awareness, you now even get Intellisense!

Try entering this (after you ran the script above and defined the new functions):

PS> Set–EnvironmentVariable –variable a –value 12 –target <#WATCH INTELLISENSE KICK IN HERE!#>

  Full Intellisense Support

Completing the Magic: Turn Function Into Module

Now that you have PowerShell functions, all that's missing is how to save them to a PowerShell module, so in the future, the new functions will be available for any PowerShell instance on your system (of course, it can be nice at times to show off a module to friends and familiy, too).

To create a new PowerShell module and store the function in it, first pick the function you want to export to a module. Note that the Code autogenerator in ISESteroids may create a bunch of functions with different signatures. Since they are all named equal, you need to choose one (or rename the others).

Next, right-click the keyword "function" in ISESteroids, and choose "Export to Module". A dialog opens, and you can now export the function to a brand new module, or add it to an existing one. Isn't that cool?

The coolness even rises, because once the module is created, the exported function is immediately available in all open PowerShell environments.

ISESteroids – Get Your Copy!

ISESteroids grows every day, and you can be part of it. Grab yourself a free trial, and if you like what you see, get a license. Licenses are cheap, compared to what you get and what others charge, and license revenues are vital for us to be able to constantly expand and improve ISESteroids.

So since ISESteroids licenses come with free unlimited updates for the version you buy, your license investment is actually coming back to you through free updates and extensions.

May the PowerShell be with you,

Tobias

Facebooktwittergoogle_pluspinterestlinkedinFacebooktwittergoogle_pluspinterestlinkedin  rssrss