问题描述
编辑:添加澄清我的愿望只是显示一个已知端(例如管道末端)的进度条,以便该函数可以提供完成的百分比(通常用于大型集在数百或数千)。我偶尔会编写函数来从管道或参数中获取对象,以便函数可以灵活。
从参数传入的对象数组的进度条非常简单,相当于先拉入完整的管道集,然后再次处理它们。我一直在避免使用后者,我只是放弃了在这种情况下的写入进度,因为它不值得影响。
我不记得我在哪里看到的,但有人提到 $PSCmdlet.MyInvocation 可能会提供计数,但也许我的理解有误。
我编写了一些接受管道输入的函数,并且经常想为通过管道进入函数的所有对象编写一个百分比进度条。
有没有办法在函数的开始获得总数?
我知道当函数循环遍历管道对象时如何增加计数器,但这只能让我知道到目前为止处理的对象数量。我想通过根据完整的管道计数来计算它的百分比。
我已经查看了 $MyInvocation 和 $PSCmdlet.MyInvocation 属性,但是无论管道集有多大,PipelineLength 和 PipelinePosition 值区域始终为“2”是。
注意:这不是我关注的解决方案,这只是我发现看起来很有希望的事情之一
这是一个测试:
Function Test-Pipeline {
[CmdletBinding()]
ParaM(
[Parameter(ValueFromPipeLine=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[psobject[]]$Path
)
BEGIN{
$PSCmdlet.MyInvocation | Select *
}
PROCESS{
ForEach ($xpath in $Path) {
$filepath = Resolve-Path $xpath | Select -ExpandProperty Path
}
}
END{}
}
当我输入 dir 的内容(该文件夹包含 20 个项目)时,我得到:
PS C:\Temp> Dir | Test-Pipeline
MyCommand : Test-Pipeline
BoundParameters : {}
UnboundArguments : {}
ScriptLineNumber : 1
OffsetInLine : 7
HistoryId : 213
ScriptName :
Line : Dir | Test-Pipeline
PositionMessage : At line:1 char:7
+ Dir | Test-Pipeline
+ ~~~~~~~~~~~~~
PSScriptRoot :
PSCommandpath :
InvocationName : Test-Pipeline
PipelineLength : 2
PipelinePosition : 2
ExpectingInput : True
CommandOrigin : Runspace
displayScriptPosition :
解决方法
正如已经评论过的那样,如果您想知道将在 cmdlet 中接收到的对象数量以预定义进度条的单位您基本上不能(在不中断流式传输过程的情况下)。
任何看起来可以做您想做的“解决方案”,实际上都会通过收集所有对象(在内存中)、对它们进行计数并最终一次性全部释放它们来阻塞整个管道。
这将违反 Strongly Encouraged Development Guidelines 到 Write Single Records to the Pipeline 并导致高内存使用率。
说明
想象一条装配线,你负责给经过你站的所有物体上色。现在您想知道今天需要完成多少个对象。 除非有人在您的站外 (cmdlet) 告诉您将跟随多少个,否则您只能通过接收所有对象计算来确定, (仍然着色它们)并传递它们。由于所有这些操作都需要时间(和物品的储藏室),下一站的人不会高兴,因为他会一次性收到所有物品,而且比预期晚了很多......
技术上
让我们构建一个从 ProcessList
生成无色对象的 cmdlet:
function Create-Object {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeLine=$true)]$ProcessList,[Switch]$Show
)
begin {
$Index = 0
}
process {
$Object = [PSCustomObject]@{
Index = $Index++
Item = $ProcessList
Color = 'Colorless'
}
if ($Show) { Write-Host 'Created:' $Object.PSObject.Properties.Value }
$Object
}
}
这就是你,给物体上色:
function Color-Object {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeLine=$true)]$InputObject,[Switch]$Show
)
process {
$InputObject.Color = [ConsoleColor](Get-Random 16)
if ($Show) { Write-Host 'Colored:' $InputObject.PSObject.Properties.Value }
$InputObject
}
}
结果如下:
'a'..'e' |Create-Object |Color-Object
Index Item Color
----- ---- -----
0 a DarkMagenta
1 b Yellow
2 c Blue
3 d Gray
4 e Green
现在让我们看看实际是如何处理的:
'a'..'e' |Create-Object -Show |Color-Object -Show
Created: 0 a Colorless
Colored: 0 a DarkGreen
Created: 1 b Colorless
Colored: 1 b DarkRed
Created: 2 c Colorless
Colored: 2 c Gray
Created: 3 d Colorless
Colored: 3 d DarkGreen
Created: 4 e Colorless
Colored: 4 e DarkGray
Index Item Color
----- ---- -----
0 a DarkGreen
1 b DarkRed
2 c Gray
3 d DarkGreen
4 e DarkGray
如您所见,第一个项目“a
”(索引 0
)着色在之前第二个项目“b
”(索引 1
)创建!
换句话说,Create-Object
还没有创建所有的对象,并且无法知道接下来会有多少。除了像之前解释的那样,你不想做的只是等待它们,并且如果有很多对象,当然要避免,对象是胖的(并且 PowerShell 对象是通常是胖的)或在输入缓慢的情况下(另请参阅:Advocating native PowerShell)。这意味着如果枚举(计数)对象对于过程的其余部分来说是微不足道的,您可能希望对此进行例外处理:例如收集文件信息 (Get-ChildItem
) 以便稍后调用繁重的进程(例如 Get-FileHash
)。
你不能在 BEGIN 中这样做。唯一的方法是将管道中的元素添加到列表中,然后在最后运行代码。
这里有一种方法可以做到这一点:
Function Test-Pipeline {
[CmdletBinding()]
PARAM(
[Parameter(ValueFromPipeLine = $true,ValueFromPipelineByPropertyName = $true)]
[Alias("FullName")]
[psobject[]]$Path
)
BEGIN {
$i = 0
$list = @()
}
PROCESS {
ForEach ($xpath in $Path) {
$list += $xpath
$i++
}
}
END {
$i
if ($i -gt 0) {
$j = 1
ForEach ($item in $list) {
Write-Output $item
Write-Progress -Activity 'activity' -Status $item.ToString() -PercentComplete (($j++)*100/$i)
Start-Sleep -Seconds 2
}
}
}
}
,
如果需要计数,可以使用 Tee-Object Cmdlet 创建一个新变量。
dir | tee-object -Variable toto | Test-Pipeline
然后
Function Test-Pipeline {
[CmdletBinding()]
PARAM(
[Parameter(ValueFromPipeLine=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[psobject[]]$Path
)
BEGIN{
$PSCmdlet.MyInvocation | Select *
$toto.count
}
PROCESS{
ForEach ($xpath in $Path) {
$filepath = Resolve-Path $xpath | Select -ExpandProperty Path
}
}
END{}
}
为我提供以下内容:
MyCommand : Test-Pipeline
BoundParameters : {}
UnboundArguments : {}
ScriptLineNumber : 1
OffsetInLine : 35
HistoryId : 11
ScriptName :
Line : dir | tee-object -Variable toto | Test-Pipeline
PositionMessage : Au caractère Ligne:1 : 35
+ dir | tee-object -Variable toto | Test-Pipeline
+ ~~~~~~~~~~~~~
PSScriptRoot :
PSCommandPath :
InvocationName : Test-Pipeline
PipelineLength : 3
PipelinePosition : 3
ExpectingInput : True
CommandOrigin : Runspace
DisplayScriptPosition :
73
和
dir | Measure-Object
Count : 73
Average :
Sum :
Maximum :
Minimum :
Property :
,
如果您编写的函数没有 Begin
、Process
和 End
块,您可以使用 $input
Automatic variable以确定通过管道发送了多少项。
$input
包含一个枚举器,用于枚举传递给函数的所有输入。 $input 变量仅可用于函数和脚本块(它们是未命名的函数)。
function Test-Pipeline {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeLine=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[psobject[]]$Path
)
$count = @($input).Count
Write-Host "$count items are sent through the pipeline"
# changed variable '$xpath' into '$item' to avoid confusion with XML navigation using XPath
foreach ($item in $Path) {
# process each item
# $filepath = Resolve-Path $item | Select -ExpandProperty Path
}
}
Get-ChildItem -Path 'D:\Downloads' | Test-Pipeline
输出类似
158 items are sent through the pipeline