tel*_*ine 6 powershell attributes function
例如:
function TestThis()
{
[MySpecialCustomAttribute]
[CmdletBinding()]
Param(...)
Process{...}
}
Run Code Online (Sandbox Code Playgroud)
任何派生Attribute
自 allowed UsageType.All
(或UsageType.Class
) 的类型都可以在函数本身上使用(即上面的Param
)
任何派生Attribute
允许UsageType.Property
或UsageType.Field
使用的类型都可以用于参数本身或变量。
只是懒惰和使用的情况并不少见UsageType.All
(例如内置OutputType
属性就是这样做的)。
using namespace System.Management.Automation
class ValidateFileExistsAttribute : ValidateArgumentsAttribute {
[void] Validate([object]$arguments, [EngineIntrinsics]$engineIntrinsics) {
if($null -eq $arguments) {
throw [System.ArgumentNullException]::new()
}
if(-not (Test-Path -Path "$arguments" -Type Leaf)) {
throw [System.IO.FileNotFoundException]::new("The specified path is not a file: '$arguments'")
}
}
}
Run Code Online (Sandbox Code Playgroud)
在Kevin Marquette的博客上查看更多示例。
这里有一个较旧的示例,展示了如何在 PowerShell 4 及更早版本中使用 Add-Type 执行此操作,尽管现在有点过时了,因为它显示的特定示例已集成到 PowerShell 6 中并且不再需要
还有视频
归档时间: |
|
查看次数: |
486 次 |
最近记录: |