【问题标题】:"Add-Member" to a type instead of only an object of that type in PowerShell在 PowerShell 中将“添加成员”添加到一个类型,而不仅仅是该类型的对象
【发布时间】:2015-02-24 09:31:56
【问题描述】:

在 PowerShell 中,您可以扩展对象:

Add-Member cmdlet 允许您将成员(属性和方法)添加到 Windows PowerShell 对象的一个​​实例。例如,您可以添加一个 NoteProperty 成员,包含对象的描述或 ScriptMethod 成员,运行脚本以更改对象。

然而:

您添加的属性和方法仅添加到 您指定的对象的特定实例。 添加成员 不改变对象类型。要创建新的对象类型,请使用 添加类型 cmdlet...

示例:

$s = "Hello World" |    Add-Member -PassThru ScriptProperty Reverse {$this[$this.Length..0] -join ""}

$s Hello World

$s.Reverse dlroW olleH

是否有一种简单直接的方式来为该类型的所有实例做同样的事情,就像 Extension Methods 在 C# 中所做的那样,会做一些类似于以下的事情:

$s = "Hello World" |    Add-Member -PassThru ScriptProperty Reverse {$this[$this.Length..0] -join ""}

$s Hello World

$s.Reverse dlroW olleH

$a = "Aymen"
$a.Reverse nemyA

【问题讨论】:

标签: c# .net windows powershell


【解决方案1】:

没有真正的简单方法可以做到这一点,但可以通过修改目标类型的类型数据来完成。这需要 Get-TypeData/Update-TypeData cmdlet。 Add-Member 无法做到这一点。下面是向 DateTime 添加属性的示例,UtcSeconds 是 UTC 时区自 1970 年 1 月 1 日以来的秒数。您也可以添加其他成员,例如方法、别名或注释属性。

$td = Get-TypeData System.DateTime
$scriptBlock = { ([System.TimeZoneInfo]::ConvertTimeToUtc($this) - (new-object System.DateTime 1970,1,1,0,0,0,0,"Utc")).TotalSeconds }
$scriptProperty = new-object System.Management.Automation.Runspaces.ScriptPropertyData "UtcSeconds", $scriptBlock
$td.Members.Add("UtcSeconds", $scriptProperty)
Update-TypeData $td -Force

请注意,如果您编写模块,则可以通过types.ps1xml file 更方便地扩展现有类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多