【问题标题】:Running Powershell command Out-File in Azure Pipeline cuts lines在 Azure Pipeline 中运行 Powershell 命令 Out-File 会切线
【发布时间】:2021-04-29 09:07:17
【问题描述】:

作为 CI 管道的一部分,我需要生成存储库中所有文件的列表,包括它们的某些属性,并将其输出到文件中。我使用的命令:

Get-ChildItem $Path -File -Recurse | Select-Object -Property LastWriteTime, @
 {
  label = "Size(KB)"
  expr = {  [string]::Format("{0:0.00}", $_.Length/1KB) } 
 }, FullName, <some_other_property> | Out-File $OutputFile
 

我的问题是,从命令行运行这个脚本会得到想要的结果。

但是,在 Azure Pipeline 构建期间运行它会做两件坏事:

  1. 在 FullName 列中的行过长时将其剪掉:
LastWriteTime     Size(KB)       Name
------------      -------        ----
<some_date>       <some size>   ASomeWhatLong...
  1. 不显示其余属性,例如

如果我将 FullName 变成 Name 一切正常,但我确实需要 FullName 属性。

因为我在气隙环境中工作,所以我无法复制所有输出和所有内容。

我尝试将-Width 标志用于Out-File,但没有成功。

【问题讨论】:

    标签: powershell azure-pipelines


    【解决方案1】:

    我相信幕后发生的事情,ps 使用创建的对象的ToString() 方法,该方法像Format-Table cmdlet 一样输出它。由于 Window 的大小,您会得到截断的属性。要查看它,您可以使用:

    (Get-Host).ui.RawUI.WindowSize
    

    这可能太小了。

    我的建议如下:

    • 将对象通过管道输入Format-Table
    Get-ChildItem $Path -File -Recurse | Select-Object -Property LastWriteTime, @
     {
      label = "Size(KB)"
      expr = {  [string]::Format("{0:0.00}", $_.Length/1KB) } 
     }, FullName, <some_other_property> | Format-Table | Out-String | Out-File $OutputFile
    

    这可能无法正常工作,但您可以使用Format-Table 的属性,例如:-Wrap。默认情况下,它会为第一个属性分配足够的空间,最后一个它会尝试“适应”它,这可能看起来像:

    LastWriteTime     Size(KB)       Name
    ------------      -------        ----
    <some_date>       <some size>   ASomeWhatLong
                                    foobarfoobarfo
                                    foobarfoobarfo
    

    要解决这个问题,您可以使用-Property 参数,它需要为:

    $propertWidth = [int]((Get-Host).ui.RawUI.WindowSize.Width / 3)
    $property = @(
        @{ Expression = 'LastWriteTime'; Width = $propertWidth; },
        @{ Expression = 'Size(KB)'; Width = $propertWidth; },
        @{ Expression = 'FullName'; Width = $propertWidth; }
    )
    
    ... | Format-Table -Property $property -Wrap | ...
    
    • 如果您不介意在文件中添加 JSON,可以使用:
    Get-ChildItem $Path -File -Recurse | Select-Object -Property LastWriteTime, @
     {
      label = "Size(KB)"
      expr = {  [string]::Format("{0:0.00}", $_.Length/1KB) } 
     }, FullName, <some_other_property> | ConvertTo-Json | Out-File $OutputFile
    

    但请注意 ConvertTo-Json 的默认 Depth2。如果您有嵌套对象,这也会截断您的对象。但就属性长度而言,它会做得很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-01
      • 2018-06-08
      • 2019-03-07
      • 2020-04-02
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多