可以获取 PowerShell 中最后执行的命令的计数吗?

发布于 2024-11-08 11:38:47 字数 378 浏览 0 评论 0原文

我正在编写一个脚本,我想吐出一堆记录,然后将计数显示为最后一行。这就是我到目前为止所拥有的:

Get-Whatever -Department $Deparment
Write-Host (Get-Whatever -Department $Deparment).Count " records found"

但我很好奇是否有一种方法可以做到这一点而无需执行两次。我以为我读过你可以在某处使用 $$ 但这不起作用。有没有更好的方法来做到这一点,或者我只需要运行两次?

我想要的输出看起来像这样:

Name
-------
Abe
Joe
Bill

3 records found

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

椒妓 2024-11-15 11:38:47

为什么不简单地将结果分配给变量呢?

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

请注意@(..)。它确保即使 Get-Whatever 不返回任何内容,$d 也将是空数组。

其他方式例如Tee-Object。但是,它有点“神奇”地创建变量,因此它不如第一种方法那么可读:

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

至于 Tee-Object (来自文档,请尝试 help tee-object -online):

Tee-Object cmdlet 发送输出
两个方向的命令(例如
字母“T”)。它存储输出
在文件或变量中并且还发送
它在管道中。如果 Tee 对象是
管道中的最后一个命令,
命令输出显示在
控制台。

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.

孤者何惧 2024-11-15 11:38:47

这应该有效:

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

This should work:

$Result = Get-Whatever -Department $Deparment
$Result; write-host "$($Result.count) records found"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文