简体   繁体   中英

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. I want to use the same csv file and run the command/script for every hour and appending the date command output. I understood that because that get-date output column data differs from the original get-service columns its throwing error. Is there any way to achieve this functionality. This mainly for reporting the service every hour in CSV file

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

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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