简短说明
描述一个属性,该属性报告函数返回的对象类型。
详细说明
OutputType 属性列出了函数返回的对象 .NET 类型。 可以使用其可选的 ParameterSetName 参数列出每个参数集的不同输出类型。
简单和高级函数都支持 OutputType 属性。
它独立于 CmdletBinding 属性。 OutputType 属性提供 cmdlet 返回的 System.Management.Automation.FunctionInfo 对象的 OutputTypeGet-Command 属性的值。
注释
OutputType 属性值不是从函数代码派生的,也不是与实际函数输出进行比较。 因此,该值可能不准确。
OutputType 属性还会通知选项卡完成结果,例如:Command | Select <Tab>和Command | Where <Tab>。
Syntax
函数 OutputType 属性具有以下语法:
[OutputType([<TypeLiteral>], ParameterSetName="<Name>")]
[OutputType("<TypeNameString>", ParameterSetName="<Name>")]
ParameterSetName 参数是可选的。
可以在 OutputType 属性中列出多个类型。
[OutputType([<Type1>],[<Type2>],[<Type3>])]
可以使用 ParameterSetName 参数来指示不同的参数集返回不同的类型。
[OutputType([<Type1>], ParameterSetName=("<Set1>","<Set2>"))]
[OutputType([<Type2>], ParameterSetName="<Set3>")]
将 OutputType 属性语句放在 param 语句前面的属性列表中。
以下示例演示简单函数中 OutputType 属性的位置。
function SimpleFunction2
{
[OutputType([<Type>])]
param ($Parameter1)
<function body>
}
以下示例显示了在高级函数中放置 OutputType 属性。
function AdvancedFunction1
{
[OutputType([<Type>])]
param (
[Parameter(Mandatory=$true)]
[string[]]
$Parameter1
)
<function body>
}
function AdvancedFunction2
{
[CmdletBinding(SupportsShouldProcess=<Boolean>)]
[OutputType([<Type>])]
param (
[Parameter(Mandatory=$true)]
[string[]]
$Parameter1
)
<function body>
}
例子
示例 1:创建具有 String OutputType 的函数
function Send-Greeting
{
[OutputType([string])]
param ($Name)
"Hello, $Name"
}
若要查看生成的输出类型属性,请使用 Get-Command cmdlet。
(Get-Command Send-Greeting).OutputType
Name Type
---- ----
System.String System.String
示例 2:使用 OutputType 属性指示动态输出类型
以下高级函数使用 OutputType 属性来指示该函数根据函数命令中使用的参数集返回不同的类型。
function Get-User
{
[CmdletBinding(DefaultParameterSetName="ID")]
[OutputType("System.Int32", ParameterSetName="ID")]
[OutputType([string], ParameterSetName="Name")]
param (
[Parameter(Mandatory=$true, ParameterSetName="ID")]
[int]
$UserID,
[Parameter(Mandatory=$true, ParameterSetName="Name")]
[string[]]
$UserName
)
<function body>
}
示例 3:显示实际输出与 OutputType 的区别
以下示例演示输出类型属性值显示 OutputType 属性的值,即使它不准确。
Get-Time 函数返回一个字符串,其中包含在任意 DateTime 对象中的时间的简短表示形式。 但是,OutputType 属性会报告它返回一个 System.DateTime 对象。
function Get-Time
{
[OutputType([datetime])]
param (
[Parameter(Mandatory=$true)]
[datetime]$DateTime
)
$DateTime.ToShortTimeString()
}
GetType() 方法确认该函数返回字符串。
(Get-Time -DateTime (Get-Date)).GetType().FullName
System.String
但是,OutputType 属性从 OutputType 属性中获取其值,报告该函数返回 DateTime 对象。
(Get-Command Get-Time).OutputType
Name Type
---- ----
System.DateTime System.DateTime
示例 4:不应具有输出的函数
下面的示例演示了一个自定义函数,该函数应执行操作,但不返回任何操作。
function Invoke-Notepad
{
[OutputType([System.Void])]
param ()
& notepad.exe | Out-Null
}
注释
FunctionInfo 对象的 OutputType 属性的值是 System.Management.Automation.PSTypeName 对象的数组,每个对象都有 Name 和 Type 属性。
若要仅获取每个输出类型的名称,请使用具有以下格式的命令。
(Get-Command Get-Date).OutputType | Select-Object -ExpandProperty Name
或者它的较短版本。
(Get-Command Get-Date).OutputType.Name
OutputType 属性的值可以为 null。 当函数不将任何输出写入 Success 流时,请使用 null 值。 如果函数写入输出,但不知道该类型,请使用 System.Object。