关于 Functions OutputTypeAttribute
简短说明
介绍报告函数返回的对象类型的属性。
详细说明
OutputType 属性列出函数返回的对象 .NET 类型。 可以使用其可选的 ParameterSetName 参数列出每个参数集的不同输出类型。
简单和高级函数支持 OutputType 属性。 它独立于 CmdletBinding 属性。
OutputType 属性提供 cmdlet 返回的 System.Management.Automation.FunctionInfo 对象的 Get-Command
OutputType 属性的值。
OutputType 属性值只是一个文档说明。 它不派生自函数代码或与实际函数输出进行比较。 因此,该值可能不准确。
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:使用 Output 属性指示动态输出类型
以下高级函数使用 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-Time).OutputType | ForEach {$_.Name}
OutputType 属性的值可以为 null。 当输出不是 .NET 类型(例如 WMI 对象或对象的格式化视图)时,请使用 null 值。
另请参阅
about_Functions_Advanced_Methods