探索PowerShell (四) PowerShell的对象、格式与参数

2019-09-30 19:21:09王旭

那么,"lastwritetime"又是什么?

我们使用如下命令看看"get-childitem"都有哪些属性可供我们筛选:

get-chileitem | get-member

可以发现其中一条:

对,就是这个。我们需要筛选出的对象属性就是最后写日期。在后面的定义中可以看到"LastWriteTime"会将一个"Syetem.DateTime"数据类型作为反馈。因此,在整个语句的后半部,我们使用了"-gt"进行进一步的筛选,"-gt"是"greater than"的缩写,意味“大于”。在以后的教程中我将会介绍更多类似这样的操作。前面说到,"LastWriteTime"是一个"Syetem.DateTime"类型的数据,因此,我们最终使用类似"01/01/2010"这样的表达。这一点需要大家多加注意,在以后的运用中需要注意数据类型。

后续的教程中,我还会尽可能全面的介绍WMI、COM以及 .NET,不过,我们现在知道并掌握上面的就足够了。

PowerShell的格式

在这一小节,我将介绍PowerShell中的格式化输出。当我们使用一个cmdlet时,参数"format-"允许我们选择一种习惯的输出模式。使用以下命令试一试:

Get-Command Format-* <enter>

其结果为:

好了,这一个知识点很简单。请各位童鞋使用如下命令试一试,结果怎么样看看就知道了。

get-childitem c:windows | format-table <enter>get-childitem c:windows | format-table -autosize <enter>get-childitem c:windows | format-custom <enter>get-childitem c:windows | format-list <enter>get-childitem c:windows | format-list -Property FullName <enter>get-childitem c:windows | format-wide <enter>

当然,复杂些的还有以下这些,我不想解释过多,大家只要肯亲自动手试一试,一眼就能看明白。

Get-ChildItem C:Windows -Recurse | Format-List -Property FullName,CreationTime,LastWriteTime<enter>

Get-ChildItem C: | Format-Wide -Column 3<enter>

另外,在其他cmdlet中,存在其他格式的输出。例如,在"get-process"中就有"group-object","Get-EventLog"中我们可能用到"Sort-Object",甚至,我们可以输出为特定格式的文件,例如使用"Convertto-HTML"输出为html,使用"Export-CSV"输出为表格文件(可以使用Excel打开)。

统统举例如下(记住管道符):

Get-Process | Group-Object Company<enter>

Get-EventLog System | Group-Object eventid<enter>

Get-EventLog System | Group-Object eventid | Sort-Object Count -descending<enter>

Get-Process | ConvertTo-html<enter>