Windows – Need a backup of entire event log of windows servers using cmd or powershell

windowswindows-event-log

I am tasked to take a backup of all the eventlogs across all the servers and retain them for 30 days. I written a simple powershell to do this.

Get-winevent  -Listlog  * | select  Logname, Logfilepath | ForEach-Object -Process { 
$name = $_.Logname
$path = $_.logfilepath
wevtutil.exe EPL $name  C:\Users\Owner\Desktop\eventlogs\$name.evtx`
}

This exports the log files for the NTclassic event logs only, for the rest of the logs i get a system cannot find the path specified error. I changed the wevtutil and included the /lf parameter and passed the $path variable, its still the same. Except for the classic logs, for everything else the below is the error i get.

wevtutil.exe : Failed to export log Microsoft-Windows-WPD-MTPClassDriver/Operational. 
The system cannot find the path specified.
At line:19 char:1
+ wevtutil.exe EPL $name  C:\Users\Owner\Desktop\eventlogs\$name.evtx
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Failed to expor...path specified.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandErrorBlockquote

is there any other better way to accomplish what i am trying to do pls ?

Best Answer

The problem is the $name variable. If you check which export files get created an which not you'll notice that all log names that contain a forward slash / generate the error message. The reason for this is that the / is an invalid character in a file name (under Windows).

You can run the export by replacing the / with a valid character:

Get-winevent  -Listlog  * | select  Logname, Logfilepath | ForEach-Object -Process { 
$name = $_.Logname
$safename = $name.Replace("/","-")
wevtutil.exe EPL $name  C:\Users\Owner\Desktop\eventlogs\$safename.evtx
}