ScriptMethods

I’ve always liked extensible languages like Perl so I’m enjoying PowerShell’s type extensibility. I’ve added several script methods or properties written by other people to my standard setup. After writing about how I had added a function to my profile.ps1 file which would convert a Guid string to “native” format, it occurred to me that I could just add that as a method to the system.guid type definition. So I added this to my My.Types.Ps1xml file:

<Type>
  <Name>System.Guid</Name>
  <Members>
    <ScriptMethod>
      <Name>ToNativeString</Name>
      <Script>
        $local:NativeGuid = “”
        $this.ToByteArray() | foreach { $NativeGuid +=  $_.tostring(“x2”) }
        $NativeGuid
      </Script>
    </ScriptMethod>
  </Members>
</Type>

 Now I can use that method like this:

PS>$Guid = new-object system.guid (“4c5efbc3-a504-4cda-8cc7-1211ad502c60”)
PS>$Guid|gm

   TypeName: System.Guid

Name           MemberType   Definition
—-           ———-   ———-
CompareTo      Method       System.Int32 CompareTo(Object value), System.Int32 CompareTo(Guid value)
Equals         Method       System.Boolean Equals(Object o), System.Boolean Equals(Guid g)
GetHashCode    Method       System.Int32 GetHashCode()
GetType        Method       System.Type GetType()
ToByteArray    Method       System.Byte[] ToByteArray()
ToString       Method       System.String ToString(), System.String ToString(String format), System.String ToString(…
MSDN           ScriptMethod System.Object MSDN();
ToNativeString ScriptMethod System.Object ToNativeString();
PS>$Guid.ToNativeString()
c3fb5e4c04a5da4c8cc71211ad502c60

And my function becomes  this:

function get-NativeGuid {
  param ($GuidString)
  (new-object system.guid ($GuidString)).ToNativeString()
}

Advertisements

One response to “ScriptMethods

  1. That is _exactly_ the right use of ScriptMethods. If you’ve got a function that only operates on one type of data, then that function is perfect candidate for a ScriptMethod / ScriptProperty.

    Lee

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s