今天我们要介绍的是PowerShell 3.0中CmdletBindingAttribute里最后一个新特性:SupportPaging。该参数可以允许用户对输出的数据进行不同的数据形势输出,尤其对于大型的数据结果输出等。
它支持以下三种:First、Skip、IncludeTotalCount
-First:只得到先前的第'n'的对象。
-Skip:忽略先前第'n'个对象数,得到剩余的数据。
-IncludeTotalCount:得到所有数据的个数。
我们先从IncludeTotalCount这个参数开始着手,看看它的作用:
Function Get-PagingInfo
{
[CmdletBinding(SupportsPaging=$true)]
Param
(
[Parameter()]
$StringData
)
If($PSCmdlet.PagingParameters.IncludeTotalCount)
{
[Double]$Accuracy = 1.0
$PSCmdlet.PagingParameters.NewTotalCount($StringData.count,$Accuracy)
}
}
如下,我们用方法配合IncludeTotalCount参数可以得到指定对象的数据个数。
Get-PagingInfo -StringData (Get-ChildItem C:\Windows) -IncludeTotalCount
Total count: 80
如下我们引用一个例子来看看如何使用skip 和 first参数:
Function Get-PagingInfo
{
[CmdletBinding(SupportsPaging = $True)]
Param
(
[Parameter()]
$StringData
)
Begin{}
Process{
}
End {
If($StringData.count -gt 0) {
If($PSCmdlet.PagingParameters.Skip -ge $StringData.count) {
Write-Verbose "No results satisfy the Skip parameters"
} Elseif($PSCmdlet.PagingParameters.First -eq 0) {
Write-Verbose "No results satisfy the First parameters"
} Else {
$First = $PSCmdlet.PagingParameters.Skip
Write-Verbose ("First: {0}" -f $First)
$Last = $First +
[Math]::Min($PSCmdlet.PagingParameters.First, $StringData.Count - $PSCmdlet.PagingParameters.Skip) - 1
}
If ($Last -le 0) {
$StringData = $Null
} Else {
$StringData = $StringData[$First..$last]
Write-Output $StringData
}
Write-Verbose ("Last: {0}" -f $Last)
}
If ($PSCmdlet.PagingParameters.IncludeTotalCount){
[double]$Accuracy = 1.0
$PSCmdlet.PagingParameters.NewTotalCount($StringData.count, $Accuracy)
}
}
}
我们可以看到列出前5条数据如下:
Get-PagingInfo -StringData (Get-ChildItem C:\Windows) -first 5
Directory: C:\Windows
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 7/26/2012 1:04 AM AppCompat
d---- 7/26/2012 1:09 AM apppatch
d-r-- 7/26/2012 1:04 AM assembly
d---- 7/26/2012 1:04 AM AUInstallAgent
d---- 7/26/2012 1:04 AM Boot
我们也可以同时搭配使用,这个命令是指跳过2条数据后,列出前5条数据。
Get-PagingInfo -StringData (Get-ChildItem C:\Windows) -first 5 -Skip 2
Directory: C:\Windows
Mode LastWriteTime Length Name
---- ------------- ------ ----
d-r-- 7/26/2012 1:04 AM assembly
d---- 7/26/2012 1:04 AM AUInstallAgent
d---- 7/26/2012 1:04 AM Boot
d---- 7/26/2012 1:04 AM Branding
d---- 7/26/2012 1:07 AM CbsTemp