簡體   English   中英

使用 Powershell 捕獲 output 數據並將日期和時間包含到 CSV 文件中

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

我正在嘗試使用 export-csv -append 將命令 output 捕獲到 CSV 文件中,並使用 out-file 將日期命令 output 添加到同一文件中。 我想使用相同的 csv 文件並每小時運行一次命令/腳本並附加日期命令 output。 我了解到,因為 get-date output 列數據與原始 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM