使用Powershell捕获数据输出并将日期和时间包含到CSV文件中
我试图使用export CSV-append将命令输出捕获到CSV文件,并使用out file将日期命令输出添加到同一文件。我想使用相同的csv文件,每小时运行一次命令/脚本,并附加日期命令输出。我理解这一点,因为get date输出列数据不同于原始的get服务列,所以抛出错误。是否有任何方法可以实现此功能。这主要用于在CSV文件中每小时报告一次服务 示例:file1.csv使用Powershell捕获数据输出并将日期和时间包含到CSV文件中,powershell,Powershell,我试图使用export CSV-append将命令输出捕获到CSV文件,并使用out file将日期命令输出添加到同一文件。我想使用相同的csv文件,每小时运行一次命令/脚本,并附加日期命令输出。我理解这一点,因为get date输出列数据不同于原始的get服务列,所以抛出错误。是否有任何方法可以实现此功能。这主要用于在CSV文件中每小时报告一次服务 示例:file1.csv 07/07/2020 Status Name DisplayName ------
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
对于
-Out File
,参数是-FilePath
而不是-Path
@AdminOfThings,-Path
是-FilePath
上下文中-FilePath
的别名(遗憾的是,这两种形式都将参数解释为通配符表达式;使用-LiteralPath
确保逐字使用)。@mklement0,无论出于何种原因,-Path
对我不起作用-LiteralPath
确实如此。感谢您的关注,@AdminOfThings:我忘记了-FilePath
的别名-Path
仅在PS[Core]v6+中可用。