首页 > 解决方案 > 使用 Powershell 捕获数据输出并将日期和时间包含到 CSV 文件中

问题描述

我正在尝试使用 export-csv -append 将命令输出捕获到 CSV 文件,并使用 out-file 将日期命令输出添加到同一文件。我想使用相同的 csv 文件并每小时运行一次命令/脚本并附加日期命令输出。我明白,因为 get-date 输出列数据与原始 get-service 列不同,所以它会抛出错误。有没有办法实现这个功能。这主要用于在 CSV 文件中每小时报告一次服务

示例:file1.csv

07/07/2020
Status   Name               DisplayName
------   ----               -----------
Stopped  AarSvc_3e53ef98    Agent Activation Runtime_3e53ef98
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Monitor Service

07/07/2020 
Status   Name               DisplayName
------   ----               -----------
Stopped  AarSvc_3e53ef98    Agent Activation Runtime_3e53ef98
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Monitor Service

错误:

PS C:\WINDOWS\system32> Get-Service | export-csv -Append -path  'D:\laptop backup\test.csv'
PS C:\WINDOWS\system32> get-date

Friday, July 10, 2020 5:10:37 PM


PS C:\WINDOWS\system32> get-date  | out-file -Append -path 'D:\laptop backup\test.csv'
Out-File : A parameter cannot be found that matches parameter name 'path'.
At line:1 char:30
+ get-date  | out-file -Append -path 'D:\laptop backup\test.csv'
+                              ~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Out-File], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.OutFileCommand

标签: powershell

解决方案


通常,添加尚不存在的属性的最佳方法是将Select-Object命令与计算的属性一起使用:

# Specify the full path to the CSV file
$CsvFile = '...'

# Get a string representation of the current date and time in whatever format is useful
$CaptureDateTime = Get-Date -Format 'yyyy-MM-dd HH:mm:ss.fff'

# Get the services, add the date and time property, and append it to the CSV file
Get-Service |
    Select-Object -Property Status, Name, DisplayName, @{n='CaptureDateTime';e={$CaptureDateTime}} |
    Export-Csv $CsvFile -NoTypeInformation -Append

推荐阅读