Saturday, 13 June 2015

Control PowerShell ResultSize (First, Last and Between)

PowerShell script may returns 1000 of records for a single command, viewing large amount of records in a single page will be difficult, so we need to restrict size of PowerShell output to view results in a better way. Some of PowerShell cmdlets may internally give support to control ResultSize of Powershell output.

Let's consider the Exchange PowerShell cmdlet Get-MailBox. Using this cmdlet, we can control PowerShell output by using the parameter -ResultSize.
Get-Mailbox -ResultSize 250
We can get unlimited results by giving ResultSize input as "Unlimited".
Get-Mailbox -ResultSize Unlimited
If you are working with a PowerShell cmdlet which doesn't support the parameter -ResultSize to control PowerShell output, in this case, you can control the result size by using Select-Object method which is generic method for all the PowerShell cmdlets.

Select First 'N' Results:

The following PowerShell command lists first 10 results.
Get-Process | Select-Object -First 10

Select Last 'N' Results:

The following PowerShell command returns last 10 results.
Get-Process | Select-Object -Last 10

Select PowerShell Output Between Specific Range:

If you are working to display PowerShell result (page by page) using page size, you need to select results between specific range size. You can select PowerShell output between specific range size by using the parameters -Skip and -First in Select-Object method.
$a = Get-process 
$a | Select-Object -Skip 10 -First 10 
The above command returns 10 processes between the index 10 and 19. The -Skip parameter skips first 10 records and the -First parameter select next 10 records, finally it returns 10 results between the index 10 to 19.

Note: -Skip (do not select) the specified number of items. By default, the Skip parameter counts from the beginning of the array or list of objects, but if the command uses the Last parameter, it counts from the end of the list or array. Unlike the Index parameter, which starts counting from 0, the Skip parameter begins at 1.


No comments:

Post a Comment