【问题标题】:Powershell append csv file after each while loopPowershell在每个while循环后附加csv文件
【发布时间】:2021-08-05 10:21:16
【问题描述】:

您能告诉我如何添加一个 csv 文件,以便将每个变量的数据写入所需的列吗?为每个新循环换一个新行?


New-Item -Path . -Name "Test.csv" -ItemType "file" -force | Out-Null
("" | Select-Object Date, RAM_1, RAM_2, RAM_3, RAM_Used_total_%, RAM_Free%, CPU_Load% | ConvertTo-Csv -NoType -Delimiter ";")[0] | Out-File '.\Test.csv'

# Start the while loops

while($true) {

# In which data is collected into variables that need to be entered into each of the columns, respectively

$date
$RAM_1
$RAM_2
$RAM_3
$RAM_Usage
$Free_RAM
$CPU_Load

    
    
    Start-Sleep -s 60
}

提前谢谢你

【问题讨论】:

  • 看看Export-Csv - 诀窍是创建具有与列对应的属性名称的对象(而不是单个变量) - 与您当前创建的方式相同带有Select-Object 的空对象

标签: powershell csv


【解决方案1】:

不要尝试手动编写 CSV 文件 - 让 Export-CSV 代您处理:

while($true) {
  # populate your variables ...
  $date = $(<# ... #>)
  $RAM_1 = $(<# ... #>)
  $RAM_2 = $(<# ... #>)
  $RAM_3 = $(<# ... #>)
  $RAM_Usage = $(<# ... #>)
  $Free_RAM = $(<# ... #>)
  $CPU_Load = $(<# ... #>)

  # then create a new object with the correct column names
  $record = [pscustomobject]@{
    'Date'              = $date
    'RAM_1'             = $RAM_1
    'RAM_2'             = $RAM_2
    'RAM_3'             = $RAM_3
    'RAM_Used_total_%'  = $RAM_Usage
    'RAM_Free%'         = $Free_RAM
    'CPU_Load%'         = $CPU_Load
  }

  # append record to CSV
  $record |Export-Csv .\path\to\output.csv -Append

  Start-Sleep -s 60
}

【讨论】:

  • 看起来您在调用 Export-Csv 之前已经在文件中写入了一些内容 - 不要那样做!如果要使用;作为分隔符,改为$record |Export-Csv .\path\to\output.csv -Append -Delimiter ';'
  • 马蒂亚斯,非常感谢!你让我开心!
  • @Irina_008 不客气!请考虑通过单击左侧的复选标记将我的答案标记为“已接受”:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 1970-01-01
  • 2020-12-31
  • 2022-01-04
  • 1970-01-01
  • 2022-01-23
  • 2014-08-21
相关资源
最近更新 更多