I am writing a script where I would like to spit out a bunch of records and then display the count as the last line. This is what I have so far:
Get-Whatever -Department $Deparment
Write-Host (Get-Whatever -Department $Deparment).Count " records found"
But i'm curious if there is a way to do it without executing it twice. I thought that I had read you could use $$
somewhere but this isn't working. Is there a better way to do this, or do I just have to run it twice?
My Desired output would look something like this:
Name
-------
Abe
Joe
Bill
3 records found
You can use Measure-Object to count objects or count objects with a specified Property. You can also use Measure-Object to calculate the Minimum, Maximum, Sum, StandardDeviation and Average of numeric values. For String objects, you can also use Measure-Object to count the number of lines, words, and characters.
Enter the command in PowerShell and press the enter key to run it. Next, run the Get-EventLog command, pipe the output to the Where-Object command, and filter by Error. Save the result of the command in a variable called $ErrorLogCount. If you wish to see a list of the error messages, run the variable, $ErrorLogCount.
After completion of the function call, the return array may be written to the console (the default), or it may be assigned to a variable, or redirected to a file, or piped to a cmdlet. Indeed, the following three kinds of console output are collected in a return array: Write-Output . A simple string reference.
Measure-Command runs the script block in the current scope, so the script block can modify values in the current scope. To avoid changes to the current scope, you must wrap the script block in braces ( {} ) and use the invocation operator ( & ) to execute the block in a child scope.
This should work:
$Result = Get-Whatever -Department $Deparment
$Result; write-host "$($Result.count) records found"
Why don't you simply assign the result to a variable?
$d = @(Get-Whatever -dep $department); $d
Write-Host $d.Count records found
Note the @(..)
. It ensures that even when Get-Whatever
doesn't return anything, $d
will be empty array.
Other way is e.g. Tee-Object
. However, it somewhat "magically" creates variables, so it is not as readable as the first approach:
Get-ChildItem | Tee-Object -var items
Write-Host $items.Count items found
As for Tee-Object
(from documentation, try help tee-object -online
):
The Tee-Object cmdlet sends the output of a command in two directions (like the letter "T"). It stores the output in a file or variable and also sends it down the pipeline. If Tee-Object is the last command in the pipeline, the command output is displayed in the console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With