PnP
PnP

Reputation: 3185

Powershell - Write to Text File

Basically I am extracting some log entries from an Event Log, formatting it, and then want to write it to a text file I will then email over. This is for Windows Server Backup monitoring purposes.

New-Item -ItemType directory -Path C:\WSBReports\
New-Item -ItemType file -Path C:\WSBReports\DailyReport.txt

$yestDate = (Get-Date) - (New-TimeSpan -day 1)
# echo $yestDate
Get-WinEvent -logname "Microsoft-Windows-Backup" |
            where {$_.timecreated -ge $yesterday} |

Format-Table TimeCreated, ID, ProviderName, Message -AutoSize -Wrap > C:\WSB_Reports\DailyReport.txt

Firstly - it says it cannot write to the file, because it doesn't exist? Even though I created it above.

And also - I think the logic is wrong as I need to always overwrite this file each time the script runs, is this possible?

Upvotes: 0

Views: 22042

Answers (2)

ray_linn
ray_linn

Reputation: 1392



Get-WinEvent -logname "Microsoft-Windows-Backup" |
            where {$_.timecreated -ge **$yesterday**} |

$yesterday is undefined since your spell for the variable is $yestDate!

My following script is working as expected


Get-WinEvent -logname "Application" | where {$_.timecreated -ge $yestDate} | format-table ItemCreated,ID,ProviderName,Message  -AutoSize -Wrap > C:\WSBReports\DailyReport.txt

Upvotes: 2

CB.
CB.

Reputation: 60958

try:

New-Item -Type directory -Path C:\WSB_Reports\

$yesterday = (Get-Date) - (New-TimeSpan -day 1)
Get-WinEvent -logname "Microsoft-Windows-Backup" |
            where {$_.timecreated -ge $yesterday} |

Format-Table TimeCreated, ID, ProviderName, Message -AutoSize -Wrap | 
out-file  C:\WSB_Reports\DailyReport.txt

Upvotes: 1

Related Questions