Upravit

Sdílet prostřednictvím


Defining Default Methods for Objects

When you extend .NET Framework objects, you can add code methods and script methods to the objects. The XML that is used to define these methods is described in the following sections.

Note

The examples in the following sections are from the Types.ps1xml types file in the Windows PowerShell installation directory ($PSHOME). For more information, see About Types.ps1xml.

Code methods

A code method references a static method of a .NET Framework object.

In the following example, the ToString method is added to the System.Xml.XmlNode type. The PSCodeMethod element defines the extended method as a code method. The Name element specifies the name of the extended method. And, the CodeReference element specifies the static method. You can also add the PSCodeMethod element to the members of the PSMemberSets element.

<Type>
  <Name>System.Xml.XmlNode</Name>
  <Members>
    <CodeMethod>
      <Name>ToString</Name>
      <CodeReference>
        <TypeName>Microsoft.PowerShell.ToStringCodeMethods</TypeName>
        <MethodName>XmlNode</MethodName>
      </CodeReference>
    </CodeMethod>
  </Members>
</Type>

Script methods

A script method defines a method whose value is the output of a script. In the following example, the ConvertToDateTime method is added to the System.Management.ManagementObject type. The PSScriptMethod element defines the extended method as a script method. The Name element specifies the name of the extended method. And, the Script element specifies the script that generates the method value. You can also add the PSScriptMethod element to the members of the PSMemberSets element.

<Type>
  <Name>System.Management.ManagementObject</Name>
  <Members>
    <ScriptMethod>
      <Name>ConvertToDateTime</Name>
      <Script>
        [System.Management.ManagementDateTimeConverter]::ToDateTime($args[0])
      </Script>
    </ScriptMethod>
  </Members>
</Type>

See also

Writing a Windows PowerShell Cmdlet