c# - 定义自定义 Powershell 对象

标签 c# powershell powershell-3.0 powershell-4.0 powershell-5.0

在 Powershell 中创建对象的方法有很多种。我将其发布为纯粹在 Powerhell 中创建对象的挑战。我正在寻找一种使用 Add-Type 创建符合这些要求的对象的方法:

  1. 强类型对象属性
  2. 实例化,使用:New-Object[My.Object]::New()[My.Object]@{'Property'= '值'}
  3. 自定义命名空间的一部分(即 [My.Object])
  4. 可以进行类型检查。示例:$myVar -is [My.Object]

我知道可以在 Visual Studio 中创建 dll 来实现这一点,但我正在寻找一种纯粹的 Powershell 方式来创建对象。

这是满足上述规则的最接近的示例:

PS C:\> $memberDef = @"
public String myString { get; set; }
public int myInt { get; set; }
"@

PS C:\> Add-Type -Namespace "My.Namespace" -Name "Object" -MemberDefinition $memberDef

PS C:\> $myObj = [My.Namespace.Object]@{'myString'='Foo'; 'myInt'=42}
PS C:\> $myObj

myString myInt
-------- -----
Foo         42

话虽如此,是否有其他(可能更好)的方法来创建外观、感觉和行为都像原生 Powershell 对象的对象?

不满足所有规则的例子

弱类型对象属性:

PS C:\> $myObj = "" | Select-Object -Property myString, myInt

PS C:\> $myObj = New-Object -TypeName PSObject -Property @{'myString'='foo'; 'myInt'=42}


PS C:\> $myObj = @{}; $myObj.myString = 'foo'; $myObj.myInt = 42

PS C:\> $myObj.myInt = "This should result in an error."

没有命名空间的对象:

PS C:\> $typeDef = @"
public class myObject {
   public string myString { get; set; }
   public int myInt { get; set; }
}
"@
PS C:\> Add-Type -TypeDefinition $typeDef
PS C:\> $myObj = [myObject]::new()

PS C:\> $myObj = New-Object -TypeName PSObject -Property @{'myString'='foo'; 'myInt'=42}
PS C:\> $myObj.PSObject.TypeNames.Insert(0, "myObject")

最佳答案

  1. Strongly-Typed object

您将获得的最接近的是显式类型变量。这可以通过在赋值过程中转换变量本身来实现:

PS C:\> [My.Namespace.Object]$myObj = [My.Namespace.Object]@{'myString'='Foo'; 'myInt'=42}
PS C:\> $myObj = 123
Cannot convert the "123" value of type "System.Int32" to type "My.Namespace.Object".
At line:1 char:1
+ $myObj = 123
+ ~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

如您所见,这导致 $myObj 只接受可以隐式转换为类型的新赋值。

关于c# - 定义自定义 Powershell 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37691681/

相关文章:

c# - 定时器(System.Threading)线程安全

powershell - 如何将时间拉到事件电源计划的 sleep 时间?

powershell - 在 PowerShell 中格式化数字以删除大于 1k 的数字 ","?

c# - 如何实现类型切换

C# 旋转 JPG 而不会损失太多质量

c# - 从多播数据包中获取发送者 ip

string - 获取 .trim/-trim、.replace/-replace、.split/-split 和其他字符串运算符的帮助

powershell - 设置位置与设置当前目录

powershell - 为什么自定义构建过程模板执行 PowerShell 失败

powershell - 如何使用 Powershell 验证保留 IP