简体   繁体   English

使用 Powershell 捕获 output 数据并将日期和时间包含到 CSV 文件中

[英]Capturing output of data and include date and time to a CSV file using Powershell

I am trying to capture the command output to a CSV file using export-csv -append and adding date command output to the same file using out-file.我正在尝试使用 export-csv -append 将命令 output 捕获到 CSV 文件中,并使用 out-file 将日期命令 output 添加到同一文件中。 I want to use the same csv file and run the command/script for every hour and appending the date command output.我想使用相同的 csv 文件并每小时运行一次命令/脚本并附加日期命令 output。 I understood that because that get-date output column data differs from the original get-service columns its throwing error.我了解到,因为 get-date output 列数据与原始 get-service 列不同,所以它的抛出错误。 Is there any way to achieve this functionality.有没有办法实现这个功能。 This mainly for reporting the service every hour in CSV file这主要用于在 CSV 文件中每小时报告一次服务

Example:file1.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

Error:错误:

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

Often, the best way to add a property which isn't already present is to use the Select-Object command with a calculated property:通常,添加尚不存在的属性的最佳方法是使用带有计算属性的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM