powershell - 为什么没有将所有 Powershell 输出写入 txt 文件

标签 powershell

我有以下在 Powershell Core 中运行的 Powershell 脚本:

 PS C:\> Get-ChildItem -Recurse -File -Filter *.pbix | 
Sort-Object -Property LastAccessTime | 
Select-object -Property Name, FullName, LastAccessTime, LastWriteTime -Last 10 
>> files.txt

打开文件 files.txt 时没有 LastAccessTime、LastWriteTime 的列 - 为什么会这样?我该如何修改脚本以便将它们包含在文本文件中?

最佳答案

两个旁白:

  • >>>Out-File -Append 的(虚拟)别名;如果目的不是附加(到一个预先存在的文件),而是只捕获当前命令的(整个)输出,则只使用>/Out-File 没有 -Append.

  • Out-File 因此也 >/>>> 捕获 for-display 表示文件中的输入对象,适合后续程序化处理。对于后者,使用生成结构化输出的 cmdlet,例如 Export-Csv .

也就是说,Out-File 捕获所有 用于显示的数据是合理的,因为文件 而不是显示是目标。

遗憾的是,从 PowerShell [Core] v7.0 开始,Out-File/>>/>>> 对(仍然)敏感控制台(终端)窗口的宽度,并且只捕获当前适合屏幕的宽度

您可以使用 Out-File使用 -Width 参数来解决这个问题:

Get-ChildItem -Recurse -File -Filter *.pbix |
  Sort-Object -Property LastAccessTime |
    Select-object -Property Name, FullName, LastAccessTime, LastWriteTime -Last 10 |
      Out-File -Width ([int]::MaxValue-1) files.txt # Add -Append, if needed.

注意:从 v7.0 开始,[int]::MaxValue-1 似乎是接受的最高值; [int]::MaxValue悄悄忽略。此外,请确保不要在 Windows PowerShell 中使用如此高的值,其中每条输出行都无条件地用右空格填充到该长度,这会导致过大文件。

关于powershell - 为什么没有将所有 Powershell 输出写入 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62628898/

相关文章:

powershell - 如果不分配给变量,为什么 Powershell Array of Array 显示不同的内容

c# - 遍历类的静态属性

powershell - 如何将 Export-CSV 链接到 Send-MailMessage 而不必在 PowerShell 中将 CSV 保存到磁盘?

powershell - Powershell脱机文件空间(Win32_OfflineFilesDiskSpaceLimit)

powershell - 找不到与参数名称 'PipelineVariable' 匹配的参数

powershell - 忽略特定行的 powershell 脚本失败

.net - 使用 .net 方法但不使用 powershell cmdlet 的文件

session - 在不退出的情况下刷新/重新启动 PowerShell session

sharepoint - Powershell 启动进程在远程 session 中被忽略

powershell - 表达式只允许作为管道的第一个元素