如何抑制PowerShell的Get-ChildItem命令的表格输出?

huangapple go评论60阅读模式
英文:

How Can I Suppress the Tabular Output from PowerShell’s Get-ChildItem?

问题

以下是翻译的部分:

在我的最新测试中,当调用Get-ChildItem时,默认的表格输出返回了超过10,000个文件的条目,使重要的数据滚动到控制台顶部之外。

不仅如此,但看到这波未请求的数据飞过真的让我的眼睛感到不适。我做过白内障和视网膜手术,我的眼睛无法承受这股洪流。

这是代码部分:

[System.IO.FileInfo[]] $queue = Get-ChildItem -path $clientRoot -recurse -attributes $ATTRIBUTE_FILTER | Where-Object `
      -filterScript {`
         ($_.fullName -notmatch $EXCLUSIONS) -and ($_.lastWriteTime -gt $lastUploadTime) `
      }

我尝试添加**| Out-Null**,它抑制了输出,但也阻止了**$queue**对象的填充。

我已经为此奋斗了两天,但没有成功。有人知道如何抑制Get-ChildItem的默认表格输出吗?

$PSVersion 表格输出:

Name                           Value
----                           -----
PSVersion                      7.3.5
PSEdition                      Core
GitCommitId                    7.3.5
OS                             Microsoft Windows 10.0.19045
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

FYI,这基本上是之前关于排序数组的一个继续问题。我在发现表格输出的来源之前提交了那个问题,这与排序无关。

英文:

When calling Get-ChildItem during my latest test, its default tabular output returns entries for over 10,000 files, and makes the important data scroll off the top of the console.

Not only that, but it literally hurts my eyes to watch the tsunami of unrequested data flying by. I’ve had cataract and retinal surgery, and my eyes just can’t handle that avalanche.

The code:

[System.IO.FileInfo[]] $queue = Get-ChildItem -path $clientRoot -recurse -attributes $ATTRIBUTE_FILTER | Where-Object `
      -filterScript {`
         ($_.fullName -notmatch $EXCLUSIONS) -and ($_.lastWriteTime -gt $lastUploadTime) `
      }

I tried adding | Out-Null, which suppressed the output, but also kept the $queue object from being populated.

I’ve been fighting this for two days, without success. Anyone know how to suppress Get-ChildItem’s default tabular output?

$PSVersion table output:

Name                           Value
----                           -----
PSVersion                      7.3.5
PSEdition                      Core
GitCommitId                    7.3.5
OS                             Microsoft Windows 10.0.19045
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

FYI, this is basically a continuation of an earlier question about sorting arrays. I submitted that question before I discovered the source of the tabular output, which is unrelated to sorting.


As requested, here’s the expanded code: Show-FileQueue calls Find-FilesWrittenSinceLastUpload, which calls Get-ChildItem.


­$ATTRIBUTE_FILTER = "!D+!H+!S+!Temporary+!Encrypted"
$EXCLUSIONS = `
   "\.bak|\.bat|\.cab|\.cmd|\.com|\.db|\.dll|\.dmp|\.exe|\.ini|\.lnk|\.log|`
   ^max-.*js$|\.msi|\.sys|\.tmp|\.temp|template|test|- Copy|New-Folder|prototype|_vti"
$lastUploadTime = A string representation of a TimeSpan object; value is "15 Jun 2023 12:24"
…
function Show-FileQueue {
   param( [switch] [bool] $ignoreLastWriteTime = $false )
   [System.IO.FileInfo[]] $queue = $null
   if ($true -eq $ignoreLastWriteTime) {
      $queue = Find-FilesWrittenSinceLastUpload -ignoreLastWriteTime $true
   } else {             
      $queue = Find-FilesWrittenSinceLastUpload 
   }
   $fileCount = ($null -eq $queue ? 0 : [int]$queue.length)
   if ($fileCount -eq 0) {
      Write-Host "Found no new/changed files`n"
   } else {
      if ($false -eq $ignoreLastWriteTime) { 
         $queue | Sort-Object -property lastWriteTime | `
         Format-Table -property name, lastWriteTime, length
      }
      $totalBytes = 0
      foreach ($file in $queue) {
         $totalBytes += $file.length
      }
      $suffix = $fileCount -eq 1 ? "" : "s"
      Write-Host $("`n{0:n0} file$suffix, {1:n0} bytes`n" -f $fileCount, $totalBytes)
   }
return $queue
______________________________________________________________

function Find-FilesWrittenSinceLastUpload {
param ( [switch] [bool] $ignoreLastWriteTime = $false )
   $clientRoot = Get-ClientRootFolder
   Confirm-NotNullOrWhiteSpace -string $clientRoot -description $CLIENT_ROOT_DESCRIPTION
   Confirm-PathExists -path $clientRoot -description $CLIENT_ROOT_DESCRIPTION

   $lastUploadTime = Get-LastUploadTime
   $message = "`nLooking for files in $clientRoot & subfolders"
   if ($false -eq $ignoreLastWriteTime) {
      $message += (", created or changed since " + $lastUploadTime)
   }
   Write-Host $message
   Write-Debug "Excluding folders & files whose names match any of these regular expressions:`n"
      $EXCLUSIONS -split "\|" | ForEach-Object{ write-debug $_ }
   Write-Debug ""

   [System.IO.FileInfo[]]$queue = $null     # So queue object is visible at return statement
   $stopwatch = [System.Diagnostics.Stopwatch]::new()
   $stopwatch.start()
   if ($true -eq $ignoreLastWriteTime) {
      $queue = Get-ChildItem -path $clientRoot -recurse -attributes $ATTRIBUTE_FILTER | Where-Object `
      fullName -notmatch $EXCLUSIONS
   } else {
      $queue = Get-ChildItem -path $clientRoot -recurse -attributes $ATTRIBUTE_FILTER | Where-Object `
      -FilterScript {`
         ($_.fullName -notmatch $EXCLUSIONS) -and ($_.lastWriteTime -gt $lastUploadTime) `
      } 
   }
   $stopwatch.stop()
   $timespan    = New-TimeSpan -milliseconds $stopwatch.ElapsedMilliseconds
   $elapsedTime = Convert-TimeSpanToString -timeSpan $timeSpan
   Write-Debug "File search completed in $elapsedTime"
   return $queue
}

答案1

得分: 0

根据Stroniax的建议,我更改了上面代码的最后一行(在不需要的输出开始出现的地方)为:

return $queue | Out-Null

然后,不需要的表格输出就消失了!我理解Out-Null的作用,但我不明白为什么这个简单的返回语句会触发不希望出现的输出。但至少我可以解决这个问题了!

感谢所有花时间查看此问题的人。如果有人知道是什么导致了一开始的奇怪行为,我很想听听解释!我每天都在学习有关PowerShell的更多知识!

英文:

As Stroniax suggested, I changed the last line of the code above (where the unwanted output began appearing) to:

return $queue | Out-Null

and the unwanted tabular output was gone! I understand what Out-Null does, but I don’t understand why that simple return statement triggered the undesired output. But at least I can put this problem to bed!

Thanks to all who took the time to look at this issue. If anyone knows what caused the weird behavior in the first place, I'd love to hear the explanation! I learn more about PowerShell every day!

huangapple
  • 本文由 发表于 2023年6月29日 08:12:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76577392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定