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:

        $local:NativeGuid = “”
        $this.ToByteArray() | foreach { $NativeGuid +=  $_.tostring(“x2”) }

 Now I can use that method like this:

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

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

And my function becomes  this:

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


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.


Leave a Reply

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

You are commenting using your 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 )

Connecting to %s