Can I get a counter for the last command executed in PowerShell?

I am writing a script where I would like to spit out a bunch of records and then display the score 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 this without doing it twice. I thought I read that you can use $$ somewhere, but that doesn't work. Is there a better way to do this, or do I just need to run it twice?

My desired output would look something like this:

 Name ------- Abe Joe Bill 3 records found 
+4
source share
2 answers

Why don't you just assign the result to a variable?

 $d = @(Get-Whatever -dep $department); $d Write-Host $d.Count records found 

Pay attention to @(..) . This ensures that even when Get-Whatever returns nothing, $d will be an empty array.

Another way is, for example, Tee-Object . However, it creates variables β€œmagically” somewhat, therefore it is not as readable as the first approach:

 Get-ChildItem | Tee-Object -var items Write-Host $items.Count items found 

Regarding Tee-Object (from the documentation, try help tee-object -online ):

The Tee-Object cmdlet sends the result of a command in two directions (for example, the letter "T"). It saves the output in a file or variable, and also pipes it. If Tee-Object is the last command in the pipeline, the output of the command is displayed in the console.

+6
source

This should work:

 $Result = Get-Whatever -Department $Deparment $Result; write-host "$($Result.count) records found" 
+3
source

All Articles