powershell - 使用 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
解决方案
通常,添加尚不存在的属性的最佳方法是将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
推荐阅读
- php - Postgress between 没有提供准确的数据
- javascript - 如何摆脱 ReferenceError: window is not defined in Java Script,这是什么意思?
- angularjs - 无法让 Angularjs 指令显示在视图中
- git - 当您的提交未通过 GitHub 检查时该怎么办?
- python - Python中的一个缺陷还是我错过了一些概念?
- ios - 嵌入在 UITabBarController 中的 UISplitViewController 在 iOS 14 中的行为很奇怪
- sql-server - Slack API MSXML2.ServerXMLHttp T-SQL 无法通过发送消息
- java - Mockito spy:尝试在间谍类方法中使用 doReturn 但使用的是原始方法
- scala - 如何将 spark.read.json 用于数据框中的多个 json 列
- visual-studio-2019 - Visual Studio 2019:无法在解决方案资源管理器中重命名文件