ValueFromPipelineByPropertyName and parameter aliases

We have not looked at parameter aliases yet. Any parameter may be given one or more aliases using the Alias attribute, as shown in the following example:

function Get-InputObject {
[CmdletBinding()]
param (
[Parameter(ValueFromPipelineByPropertyName)]
[Alias('First', 'Second', 'Third')]
$InputObject
)
}

The alias name is considered when determining whether a property on an input object is suitable to fill a parameter when filling a parameter by property name.

One of the more common uses of this is to provide support for a Path parameter via a pipeline from Get-Item or Get-ChildItem. For example, the following pattern might be used to expose a Path parameter. This is used in the short helper function that imports JSON content from a file:

function Import-Json {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[Alias('PSPath')]
[String]$Path
)

process {
Get-Content $Path | ConvertFrom-Json
}
}

The PSPath property of the object returned by Get-Item or Get-ChildItem is used to fill the Path parameter from a pipeline. FullName is a possible alternative to PSPath, depending on how the path is to be used.

Converting relative paths to full paths

When using a path parameter, such as the one in the previous example, the following method on the PSCmdlet object can be used to ensure a path is fully qualified whether it exists or not:

$Path = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)

This technique is useful if working with .NET types, which require a path as these are not able to resolve PowerShell paths (either relative or via a PS drive).

The New-TimeSpan command is an example of an existing command that uses the alias to fill a parameter from the pipeline. The Start parameter has an alias of LastWriteTime. When Get-Item is piped into New-TimeSpan, the time since the file or directory was last written will be returned as a TimeSpan via the aliased parameter.

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

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