【问题标题】:What is the difference between piping and round brackets for PowerShell Get-FileHash?PowerShell Get-FileHash 的管道和圆括号有什么区别?
【发布时间】:2019-10-24 12:07:41
【问题描述】:

以下两个使用 Get-FileHash cmdlet 的命令似乎给出了相同的结果(目录及其子目录中所有文件的 md5 哈希)。我想知道除了字符数之外,文件路径列表中的管道和使用圆括号到 Get-FileHash cmdlet 之间是否有任何区别?

Get-FileHash -Algorithm MD5 -Path (Get-ChildItem "*.*" -Recurse)

Get-ChildItem "*.*" -Recurse | Get-FileHash -Algorithm MD5

另外,我尝试用 Measure-Command 对命令计时十几次(基于这个问题 Timing a command's execution in PowerShell;我不知道 PowerShell 中有一种更具统计意义的方法)——在同一个小目录上在我的系统中,圆括号版本通常需要 8 到 9 毫秒,而管道版本需要 9 到 10 毫秒。

Measure-Command { Get-FileHash -Algorithm MD5 -Path (Get-ChildItem "*.*" -Recurse) }

Measure-Command { Get-ChildItem "*.*" -Recurse | Get-FileHash -Algorithm MD5 }

【问题讨论】:

  • 第一个版本读取高优先级 perens 部分中的文件并将其放入 -Path 参数值。第二个读取文件信息并将其传送到接受byNamebyValue 的cmdlet 到-Path 参数中。 ///// 使用大量 enuf 文件,第一个会更快,因为它避免了管道 [slow-ish] 和为推断参数分配值所需的解析。
  • 在我的脑海中,Piping 会将每个文件对象传递给Get-FileHash 函数,因为括号中的命令版本将运行对象数组。我现在用更大的样本量来证实这一点。

标签: powershell


【解决方案1】:

以更大的样本量运行,随心所欲。将 GCI 分配给变量然后将其用作 Get-FileHash 参数似乎更快。

也如 cmets 中所述。 Bracketed 是一个数组,其中管道会将每个对象“推送”到函数。管道通常较慢。

将这些数字运行大约 15 次,并保留最后的结果,因为它们非常相似。

(Get-ChildItem "*.*" -Recurse).Count
(Measure-Command { Get-FileHash -Algorithm MD5 -Path (Get-ChildItem "*.*" -Recurse) }).TotalSeconds
(Measure-Command { Get-ChildItem "*.*" -Recurse | Get-FileHash -Algorithm MD5 }).TotalSeconds
(Measure-Command { $Test = Get-ChildItem "*.*" -Recurse}).TotalSeconds + (Measure-Command {(get-FileHash -Algorithm MD5 $Test)}).TotalSeconds

# Total Files: 5244
# Seconds to run Bracketed GCI: 18.3848352
# Seconds to run Piped GI: 19.751385
# Seconds to run GCI to Object + Paramed hash: 17.5382904 (1.3471413 + 16.1911491)

【讨论】:

    猜你喜欢
    • 2016-06-26
    • 2012-04-05
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2021-05-16
    相关资源
    最近更新 更多