Windows Powershell创建对象

.Net类型中的方法功能很强大。可以通过类型的构造函数创建新的对象,也可以将已存在的对象转换成指定的类型。

通过New-Object创建新对象

如果使用构造函数创建一个指定类型的实例对象,该类型必须至少包含一个签名相匹配的构造函数。例如可以通过字符和数字创建一个包含指定个数字符的字符串:

复制代码 代码如下:

PS C:Powershell> New-Object String(‘*',100)

*******************************************************************************
*********************

为什么支持上面的方法,原因是String类中包含一个Void .ctor(Char, Int32) 构造函数

复制代码 代码如下:

PS C:Powershell> [String].GetConstructors() | foreach {$_.tostring()}
Void .ctor(Char*)
Void .ctor(Char*, Int32, Int32)
Void .ctor(SByte*)
Void .ctor(SByte*, Int32, Int32)
Void .ctor(SByte*, Int32, Int32, System.Text.Encoding)
Void .ctor(Char[], Int32, Int32)
Void .ctor(Char[])
Void .ctor(Char, Int32)

通过类型转换创建对象

通过类型转换可以替代New-Object

复制代码 代码如下:

PS C:Powershell> $date="1999-9-1 10:23:44"
PS C:Powershell> $date.GetType().fullName
System.String
PS C:Powershell> $date
1999-9-1 10:23:44
PS C:Powershell> [DateTime]$date="1999-9-1 10:23:44"
PS C:Powershell> $date.GetType().FullName
System.DateTime
PS C:Powershell> $date

1999年9月1日 10:23:44

以上就是Windows Powershell创建对象的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 脚本专栏