The PSTypeName attribute

It is not uncommon in PowerShell to want to pass an object created in one command, as a PSObject (or PSCustomObject), to another. The PSTypeName attribute is able to test the type name assigned to a custom object. Type names are assigned by setting (or adding) a value to the hidden PSTypeName property. There are a number of ways to tag PSCustomObject with a type name. The simplest is to set a value for a PSTypeName property, shown as follows:

$object = [PSCustomObject]@{
Property = 'Value'
PSTypeName = 'SomeTypeName'
}

The PSTypeName property remains hidden, but Get-Member will now show the new type name:

PS> $object | Get-Member

TypeName: SomeTypeName

Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Property NoteProperty string Property=Value

It is also possible to tweak the PSTypeNames array directory, shown as follows:

$object = [PSCustomObject]@{ Property = 'Value' }

# Add to the end of the existing list
$object.PSTypeNames.Add('SomeTypeName')


# Or add to the beginning of the list
$object.PSTypeNames.Insert(0, 'SomeTypeName')

Finally, Add-Member can add to PSTypeNames. If used, it adds the new type name at the top of the existing list:

$object = [PSCustomObject]@{ Property = 'Value' }
$object | Add-Member -TypeName 'SomeTypeName'

These tagged types may be tested using the PSTypeName attribute of a parameter, for example:

function Test-PSTypeName {
[CmdletBinding()]
param (
[PSTypeName('SomeTypeName')]
$InputObject
)
}

This technique is used by many of the WMI-based commands implemented by Microsoft. For example, the Set-NetAdapter command uses a PSTypeName attribute for its InputObject parameter:

(Get-Command Set-NetAdapter).Parameters['InputObject'].Attributes |
Where-Object TypeId -eq ([PSTypeNameAttribute])

In the case of the WMI-based commands, this is used in addition to a .NET type name, an array of CimInstance. This type of parameter is similar to the following example:

function Test-PSTypeName {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'InputObject (cdxml)')]
[PSTypeName('Microsoft.Management.Infrastructure.CimInstance#MSFT_NetAdapter')]

[CimInstance[]]$InputObject
)
}

This technique is incredibly useful when the .NET object type is not sufficiently detailed to restrict input. This is true of PSObject input as much as the CimInstance array type used before.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.23.126.63