【问题标题】:Capturing output of data and include date and time to a CSV file using Powershell使用 Powershell 捕获数据输出并将日期和时间包含到 CSV 文件中
【发布时间】:2020-07-11 09:26:48
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 对于Out-File,参数是-FilePath而不是-Path
  • @AdminOfThings, -Path-FilePathOut-File 上下文中的别名(遗憾的是,这两种形式都将参数解释为通配符表达式;使用-LiteralPath 确保逐字使用)。
  • @mklement0,无论出于何种原因,-Path 对我不起作用。但是,-LiteralPath 确实如此。
  • 感谢@AdminOfThings 的跟进:我忘记了-FilePath 的别名-Path 仅在PS [Core] v6+ 中可用。

标签: powershell


【解决方案1】:

通常,添加不存在的属性的最佳方法是使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 2018-04-23
    • 1970-01-01
    • 2020-11-14
    • 2015-06-14
    • 1970-01-01
    • 2016-11-25
    相关资源
    最近更新 更多