Powershell使用真实的对象工作 3


每一个Powershell命令都会返回一个对象,但是返回的对象不易操作,因为控制台解释器会自动将对象转换成可视的文本,这样就会丢失绝大多数对象的信息。

在变量中存储结果

不要将结果在控制台输出可以防止对象转换成文本。控制台是一个不安全的地方,任何对象输出后都会自动转换成文本,最安全的方式是将对象保存在变量中。如果想将对象输出为文本,可以在控制台输入变量名。

PS C:Powershell> $FileList=dir
PS C:Powershell> $FileList

    目录: C:Powershell

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2011/12/19     17:43       8956 a.ccs
-a---        2011/12/19     18:02      46411 a.csv

事实上述存储在$FileList变量中的并不是真实的对象,而是一个对象数组,数组可以通过索引访问得到真实的对象。

PS C:Powershell> $obj=(dir)[0]
PS C:Powershell> $obj

    目录: C:Powershell

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2011/12/19     17:43       8956 a.ccs

使用对象的属性

可以使用Get-Member得到一个对象所有的属性:

PS C:Powershell> $obj=(dir)[0]
PS C:Powershell> $obj | Get-Member -MemberType Property

   TypeName: System.IO.FileInfo

Name              MemberType Definition
----              ---------- ----------
Attributes        Property   System.IO.FileAttributes Attributes {get;set;}
CreationTime      Property   System.DateTime CreationTime {get;set;}
CreationTimeUtc   Property   System.DateTime CreationTimeUtc {get;set;}
Directory         Property   System.IO.DirectoryInfo Directory {get;}
DirectoryName     Property   System.String DirectoryName {get;}
Exists            Property   System.Boolean Exists {get;}
Extension         Property   System.String Extension {get;}
FullName          Property   System.String FullName {get;}
IsReadOnly        Property   System.Boolean IsReadOnly {get;set;}
LastAccessTime    Property   System.DateTime LastAccessTime {get;set;}
LastAccessTimeUtc Property   System.DateTime LastAccessTimeUtc {get;set;}
LastWriteTime     Property   System.DateTime LastWriteTime {get;set;}
LastWriteTimeUtc  Property   System.DateTime LastWriteTimeUtc {get;set;}
Length            Property   System.Int64 Length {get;}
Name              Property   System.String Name {get;}

如果属性的定义列中包含{get;set}表明该属性可以被更新:

PS C:Powershell> $obj.LastAccessTime

2011年12月19日 17:43:37

PS C:Powershell> $obj.LastAccessTime=Get-Date
PS C:Powershell> $obj.LastAccessTime

2012年1月11日 14:21:01

Powershell特殊属性

Powershell中 可以给一个对象增加属性,增加的属性仍然可以通过Get-Member的标签辨别,因为对象的正常属性标签名为:Property,新增加的属性标签多了一个前缀,如ScriptProperty和NoteProperty。
一个NoteProperty包含了静态的数据。一个ScriptProperty中包含了一段脚本,通过脚本计算出属性的值。
下面的例子新建一个对象$obj,给$obj增加两个属性一个为NoteProperty,一个为ScriptProperty,输出$obj ,CurrentTime属性会自动更新,AddTime则不会。

PS C:Powershell> $obj=New-Object PSobject
PS C:Powershell> $obj | Add-Member -MemberType NoteProperty -Name AddTime -Value (get-date)
PS C:Powershell> $obj | Add-Member -MemberType ScriptProperty -Name CurrentTime -Value {get-date}
PS C:Powershell> $obj

AddTime                                                     CurrentTime
-------                                                     -----------
2012/1/11 14:35:38                                          2012/1/11 14:36:35

PS C:Powershell> $obj

AddTime                                                     CurrentTime
-------                                                     -----------
2012/1/11 14:35:38                                          2012/1/11 14:36:44

MemberType包括:
AliasProperty:另外一个属性的别名
CodeProperty:通过静态的.Net方法返回属性的内容
Property:真正的属性
NoteProperty:随后增加的属性
ScriptProperty:通过脚本执行返回一个属性的值
ParameterizedProperty:需要传递参数的属性

调用对象的方法

同样可以通过Get-Memeber获得一个对象支持的所有方法:

PS C:Powershell> $obj= (dir)[0]
PS C:Powershell> $obj | Get-Member -me method

   TypeName: System.IO.FileInfo

Name                      MemberType Definition
----                      ---------- ----------
AppendText                Method     System.IO.StreamWriter AppendText()
CopyTo                    Method     System.IO.FileInfo CopyTo(string destFileName), System.IO.FileInfo CopyTo(strin...
Create                    Method     System.IO.FileStream Create()
CreateObjRef              Method     System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateText                Method     System.IO.StreamWriter CreateText()
Decrypt                   Method     System.Void Decrypt()
Delete                    Method     System.Void Delete()
Encrypt                   Method     System.Void Encrypt()
Equals                    Method     bool Equals(System.Object obj)
GetAccessControl          Method     System.Security.AccessControl.FileSecurity GetAccessControl(), System.Security....
GetHashCode               Method     int GetHashCode()
GetLifetimeService        Method     System.Object GetLifetimeService()
GetObjectData             Method     System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo info, ...
GetType                   Method     type GetType()
InitializeLifetimeService Method     System.Object InitializeLifetimeService()
MoveTo                    Method     System.Void MoveTo(string destFileName)
Open                      Method     System.IO.FileStream Open(System.IO.FileMode mode), System.IO.FileStream Open(S...
OpenRead                  Method     System.IO.FileStream OpenRead()
OpenText                  Method     System.IO.StreamReader OpenText()
OpenWrite                 Method     System.IO.FileStream OpenWrite()
Refresh                   Method     System.Void Refresh()
Replace                   Method     System.IO.FileInfo Replace(string destinationFileName, string destinationBackup...
SetAccessControl          Method     System.Void SetAccessControl(System.Security.AccessControl.FileSecurity fileSec...
ToString                  Method     string ToString()

调用一个对象的方法时,省略括号可以获取一个方法的详细定义信息:

PS C:Powershell> $obj.CreationTime

2011年12月19日 17:43:37

PS C:Powershell> $obj.MoveTo

MemberType          : Method
OverloadDefinitions : {System.Void MoveTo(string destFileName)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.Void MoveTo(string destFileName)
Name                : MoveTo
IsInstance          : True

调用对象的Delete方法:

PS C:Powershell> Test-Path $obj
True
PS C:Powershell> $obj.Delete()
PS C:Powershell> Test-Path $obj
False

不同的方法类型

类似于属性,Powershell对象也可以增加方法,方法类型包括:
CodeMethod:映射到静态的.NET方法
Method:正常的方法
ScriptMethod:一个执行Powershell脚本的方法

本文链接: https://www.pstips.net/powershell-work-with-reallife-objects.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

回复 Mooser Lee 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

3 条评论 “Powershell使用真实的对象工作