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|gmTypeName: 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()
}
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