Export windows logs to csv each 1 hour - powershell

I really need your help, I already make a script for export logs to csv file:
Set-Variable -Name EventAgeDays -Value 1
Set-Variable -Name CompArr -Value #("Localhost")
Set-Variable -Name LogNames -Value #("Security", "Application", "System")
Set-Variable -Name EventTypes -Value #("Information", "Error", "Warning", "FailureAudit", "SuccessAudit")
Set-Variable -Name ExportFolder -Value "C:\"
$el_c = #()
$now = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($(Get-Date), [System.TimeZoneInfo]::Local.Id, 'GMT Standard Time')
$startdate=$now.adddays(-$EventAgeDays)
$ExportFile=$ExportFolder + "mx_sugus_poc_" + $now.ToString("yyyy.MM.dd_hh.mm") + ".csv"
foreach($comp in $CompArr)
{
foreach($log in $LogNames)
{
Write-Host Processing $comp\$log
$el = get-eventlog -ComputerName $comp -log $log -After $startdate -EntryType $EventTypes -Message "*"
$el_c += $el
}
}
$el_sorted = $el_c | Sort-Object TimeGenerated
Write-Host Exporting to $ExportFile
$el_sorted|Select TimeGenerated, EntryType, Source, EventID, MachineName, UserName, Message | export-CSV $ExportFile -NoTypeInfo
Additional I change the date for a GMT format.
I want to change the search in my logs instead of every day for every hour.
Can you help me with this ???
Thanks so much !!!

Change $startdate=$now.adddays(-$EventAgeDays) to $startdate=$now.addHours(-1)

Related

Export Eventlogs and send email

I have written a script to export specific Eventvwr logs based on Source and the script is working as expected, but i am trying to cut short the message form the Eventvwr, i dont to print entire message on the mail.
I am attaching the output of my code below
#
# This script exports consolidated and filtered event logs to CSV
#
#Application error and critical eventlogs for specific EventID:
#Email Details
$FromAddress = 'abc.com'
$ToAddress = '123.com'
$SmtpServer = 'xyz.com'
Set-Variable -Name EventAgeDays -Value 4 #we will take events for the latest 7 days
Set-Variable -Name CompArr -Value #("abcedf.com") # replace it with your server names
Set-Variable -Name LogNames -Value #("Application") # Checking app and system logs
Set-Variable -Name EventTypes -Value #("Information") # Loading only Errors and Warnings
Set-Variable -Name ExportFolder -Value "C:\xxx\"
Set-Variable -Name Source -Value #("123", "111")
$el_c = #() #consolidated error log
$now=get-date
$startdate=$now.adddays(-$EventAgeDays)
$ExportFile=$ExportFolder + "Out" + $now.ToString("yyyy-MM-dd---hh-mm-ss") + ".csv" # we cannot use standard delimiteds like ":"
foreach($comp in $CompArr)
{
foreach($log in $LogNames)
{
foreach ($src in $Source)
{
Write-Host Processing $comp\$log
$el = get-eventlog -ComputerName $comp -log $log -After $startdate -EntryType $EventTypes -Source $src -Newest 1 -InstanceId 30000
$el_c += $el #consolidating
#}
#}
$el_sorted = $el_c | Sort-Object TimeGenerated #sort by time
Write-Host Exporting to $ExportFile
}
}
}
$out = $el_sorted|Select MachineName, EntryType, TimeGenerated, Source, EventID, Message #| Export-CSV $ExportFile -NoTypeInfo #EXPORT
Write-Host Done!
$msgBody = $out
Send-MailMessage -from $FromAddress -to $ToAddress -SmtpServer $SmtpServer -Subject "TL Stage Ingester Status from $CompArr $startdate" -Body ( $msgBody | Out-String)

Pulling all logs from various servers to excel - Having trouble pulling extra logs

For the last day, I have been working on a script to pull logs from various servers. I have found a script that does this and I have built on it.
So far I can pull application and system logs. However, I am having trouble pulling security logs. If I run the Get-EventLog Security it works fine on its own, but when I try adding to my script below it does not pull the logs.
Set-Variable -Name EventAgeDays -Value 7 #takes events for the latest 7 days - change the number as required
Set-Variable -Name CompArr -Value #("Serv1, serv2, serv3") # replace it with the server names - FOR TESTING I HAVE USED MY MACHINE NAME
Set-Variable -Name LogNames -Value #("Application", "System") # Checking app logs, system logs and security logs
Set-Variable -Name EventTypes -Value #("Error", "Warning") # Loading only Errors and Warnings
Set-Variable -Name ExportFolder -Value "C:\test.csv" # Create excel file called "test"
$mLog_c = #() #consolidated error log
$now = Get-Date
$startdate = $now.AddDays(-$EventAgeDays)
# creates .csv file with the date and time when the script was run on
# the end of "test.csv"
$ExportFile = $ExportFolder + "Log" + $now.ToString("dd-MM-yyyy---hh-mm-ss") + ".csv"
foreach ($comp in $CompArr) {
foreach ($el in $LogNames) {
Write-Host Processing $comp\$log
$el = Get-EventLog -ComputerName $comp -Log $log -After $startdate -EntryType $EventTypes
$el_c += $el #consolidating
}
}
$log_sorted = $el_c | Sort-Object TimeGenerated #sort by time
Write-Host Exporting to $ExportFile
$log_sorted |
Select Date, ServerName, EntryType, TimeGenerated, Source, EventID,
PID, TID, Component, message |
Export-Csv $ExportFile -NoTypeInfo #EXPORT COMMAND
Write-Host Completed #Completed once finished

Powershell Get-EventLog output issue when logging

I am having an issue with the writing of a get-eventlog function when I'm writing to a TXT file.
This is my LogWrite function:
#Log Function
$Logfile = "..\Logs\$(gc env:computername)_Outlook.log"
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
Function LogWrite
{
Param ([string]$logstring)
Add-content $Logfile -value $Stamp": "$logstring -Force
}
This is my LogWrite code in part of my script.
$OutlookHangDetailed = Get-EventLog -Log "Application" -Source "Application Hang" -Message "*OUTLOOK.EXE*" -After (Get-Date).AddHours(-12) -ErrorAction SilentlyContinue
LogWrite $OutlookHangDetailed | Format-List
The issue I am having is its coming out like this in the txt file:
Microsoft.PowerShell.Commands.GenericMeasureInfo
But if I simply echo it, it comes out like this (This is an example):
Index : 2568
EntryType : Information
InstanceId : 15
Message : Updated Symantec Endpoint Protection status successfully to SECURITY_PRODUCT_STATE_ON.
Category : (0)
CategoryNumber : 0
ReplacementStrings : {Symantec Endpoint Protection, SECURITY_PRODUCT_STATE_ON}
Source : SecurityCenter
TimeGenerated : 3/15/2017 7:46:02 AM
TimeWritten : 3/15/2017 7:46:02 AM
How can I get this to write to the log this way?
There is no output from your log function. You are not piping anything into Format-List
$OutlookHangDetailed is going to be an array of objects of [System.Diagnostics.EventLogEntry]. You can turn it into a string with $logstring | fl | out-string. Casting directly to a string isn't going to give you the output you are looking for.
$Logfile = "..\Logs\$(gc env:computername)_Outlook.log"
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
Function LogWrite {
Param (
[System.Diagnostics.EventLogEntry[]]$logstring,
[string]$Logfile,
[string]$Stamp
)
$logentry = "$($Stamp):$($logstring | fl | out-string)"
Add-Content $Logfile -value $logentry -Force
$logentry
}
$OutlookHangDetailed = Get-EventLog -Log "Application" -Source "Application Hang" -Message "*OUTLOOK.EXE*" -After (Get-Date).AddHours(-12) -ErrorAction SilentlyContinue
LogWrite $OutlookHangDetailed $Logfile $Stamp
Get-EventLog -Log "Application" -Source "Application Hang" -Message "*OUTLOOK.EXE*" -After (Get-Date).AddHours(-12) -ErrorAction SilentlyContinue >> "..\Logs\$(gc env:computername)_Outlook.log"
This will work as expected
Maybe like this:
Function LogWrite
{
param (
$logstring
)
$Stamp | Out-File -Encoding UTF8 -FilePath $Logfile -Append -Force
($logstring | Format-List) | Out-File -Encoding UTF8 -FilePath $Logfile -Width 1024 -Append -Force
}
And call your function with:
LogWrite $OutlookHangDetailed

Invoke-Command: Null-value and positional parameter errors

I wanted to start a new thread for this, since I am using a different method in my code now. I have written a script that pings hundreds of devices and logs their online or offline status. It was taking an extremely long time to run, so I am now looking into using Invoke-Command to run the commands remotely on servers for each site (instead of all from the same server). I am receiving the following errors: "A positional parameter cannot be found that accepts argument 'Of'", "You cannot call a method on a null-valued expression", and this is happening for each server as it is iterating through them. Any ideas as to why this is happening? Thank you very much, here is my current code:
<#
.NOTES
===========================================================================
Created on: 11/17/2016 8:06 AM
Created by:
Organization:
Filename: Get-MPOSOfflinePrinters.ps1
===========================================================================
.DESCRIPTION
#>
#Define log file variables and remove any existing logs
$logfile = "D:\Logs\MPOSPrinterPingLog.txt"
$offlineprinters = "D:\Reports\MPOS\MPOSOfflinePrinters.txt"
If (Test-Path $logfile) {Remove-Item $logfile}
If (Test-Path $offlineprinters) {Remove-Item $offlineprinters}
Add-Content $logfile "Gathering server list"
#Compiling list of all MPOS Print Servers
$serverList = (Get-ADComputer -Filter "Name -like 'Q0*P30' -or Name -like 'Q0*P32'" -SearchBase "OU=Print,OU=Prod,OU=POS,DC=COMPANY,DC=NET").name | Sort-Object | Out-File C:\Temp\MPOS\MPOSPrintServers.txt
$serverListPath = "C:\Temp\MPOS\MPOSPrintServers.txt"
Add-Content $logfile "Compiling text file"
#Retrieve a list of MPOS Print servers from text file and set to variable $serverNames
$serverNames = Get-Content -Path $serverListPath
Invoke-Command -ComputerName $serverNames -ScriptBlock {
#Define log file variables and remove any existing logs
$logfile = "C:\Temp\MPOSPrinterPingLog.txt"
$offlineprinters = "C:\Temp\MPOSOfflinePrinters.txt"
$masteroffline = "\\a0345p689\d$\Reports\MPOS\MPOSOfflinePrinters.txt"
If (Test-Path $logfile) {Remove-Item $logfile}
If (Test-Path $offlineprinters) {Remove-Item $offlineprinters}
#process xml file to parse IP addresses for ping
$timestamp2 = (Get-Date -Format g)
Add-Content $logfile "$timestamp2 - Processing xml file from $serverName to parse data to csv"
$xml = [xml](Get-Content C:\ProgramData\Microsoft\Point Of Service\Configuration\Configuration.xml)
$PrinterNames = $xml.selectNodes('//PointOfServiceConfig/ServiceObject/Device') | foreach {New-Object -TypeName psobject -Property #{LogicalName=$_.LogicalName.Name}}
$PrinterIPs = $xml.selectNodes('//PointOfServiceConfig/ServiceObject/Device') | foreach {New-Object -TypeName psobject -Property #{HardwarePath=$_.HardwarePath}}
foreach ($PrinterIP in $PrinterIPs) {
$pingableIP = $PrinterIP.HardwarePath
If (Test-Connection $pingableIP -Quiet -Count 1) {
$timestamp3 = (Get-Date -Format g)
Add-Content $logfile "$timestamp3 - $serverName, $pingableIP is online and pingable"
}
Else {
$timestamp3 = (Get-Date -Format g)
Add-Content $offlineprinters "$timestamp3 - $serverName, $pingableIP is offline!"
}
Get-Content $offlineprinters | Out-File -FilePath $masteroffline -Append -NoClobber
} #foreach ($PrinterIP in $PrinterIPs) {
} #Invoke-Command -ComputerName $serverNames -ScriptBlock {

How to Add Date/Time to Each Line before exporting to CSV

I've got a nice working powershell function called PSO.
The PSO function searches for one or more specific windows processes based on the given input/parameter. When a procesname matches the searchparameter it exports/appends the process owner and more info to a csv file. All good so far.
Now I really like to add date and time info to each line PowerShell writes to the csv. I've been struggling with it for a while now. I've got somehting simular working in VBScript, but i'm really starting to like powershell and like to see and learn more.
Below The PSO Function, I assume this is the area where Date and Time should be generated and added... right?
Function Get-PSO($searchString)
# http://powershell.com/cs/blogs/tips/archive/2009/12/17/get-process-owners.aspx
# Usage: Get-PSO * OR Get-PSO exp*,*paint*,calc*,notepad*
# Sample Export2csv: Get-PSO notepad* | Export-CSV $env:userprofile\desktop\export.csv -Append
# A few date/time formats for later use... i hope
$date=(Get-Date -format "yyyy-MM-d")
$time=(Get-Date -format "HH:mm:ss")
$datetime=(Get-Date -format "yyyy-MM-d HH:mm")
$foundProcess = ps $searchString -ea silentlycontinue
if($foundProcess -eq $null) { return; }
$foundprocess | % {
gwmi Win32_Process -Filter ("Handle={0}" -f $_.id ) |
% { Add-Member -TypeName Type -InputObject $_ -MemberType NoteProperty -Name Owner -Value ($_.GetOwner().User) -PassThru } |
# See below my last attempt to get this tot work
# % { Add-Member -TypeName Type -InputObject $_ -MemberType NoteProperty -Name Owner -Value ($_.GetOwner().User) -MemberType NoteProperty -Name Date -Value $date -PassThru } |
select Name, Handle, Owner, Type
}
When I run the function ; Get-PSO notepad* | Export-CSV $env:userprofile\desktop\export.csv -Append) I get the following result:
Name;Handle;Owner;Type
notepad++.exe;7736;Dave;
I like to Add Date/Time and the result should look something like:
Name;Handle;Owner;Date;Time;DateTime;Type
notepad++.exe;7736;Dave;5-4-2015;20:07;5-4-2015 20:07;
Anyone? some help or ideas would be very much appreciated.
Is this what you are looking for?
Function Get-PSO($searchString) {
# http://powershell.com/cs/blogs/tips/archive/2009/12/17/get-process-owners.aspx
# Usage: Get-PSO * OR Get-PSO exp*,*paint*,calc*,notepad*
# Sample Export2csv: Get-PSO notepad* | Export-CSV $env:userprofile\desktop\export.csv -Append
# A few date/time formats for later use... i hope
$date=(Get-Date -format "yyyy-MM-d")
$time=(Get-Date -format "HH:mm:ss")
$datetime=(Get-Date -format "yyyy-MM-d HH:mm")
$foundProcess = ps $searchString -ea silentlycontinue
if($foundProcess -eq $null) { return; }
$foundprocess | % {
gwmi Win32_Process -Filter ("Handle={0}" -f $_.id ) |
% {
Add-Member -InputObject $_ -MemberType NoteProperty -Name Owner -Value ($_.GetOwner().User) -PassThru
Add-Member -InputObject $_ -MemberType NoteProperty -Name Date -Value $date -PassThru
Add-Member -InputObject $_ -MemberType NoteProperty -Name Time -Value $time -PassThru
Add-Member -InputObject $_ -MemberType NoteProperty -Name DateTime -Value $datetime -PassThru
Add-Member -InputObject $_ -MemberType NoteProperty -Name Type -Value "" -PassThru
} |
select Name, Handle, Owner, Date, Time, DateTime, Type
}
}
Each Add-Member command adds a property to the individual results. The Name parameter will be the column name in the exported CSV and the Value parameter will be the value. The select command (actually Select-Object) filters the results to the listed subset of properties.
Alternatively, you could do all of this using just Select-Object and Calculated Properties.
Function Get-PSO($searchString) {
# http://powershell.com/cs/blogs/tips/archive/2009/12/17/get-process-owners.aspx
# Usage: Get-PSO * OR Get-PSO exp*,*paint*,calc*,notepad*
# Sample Export2csv: Get-PSO notepad* | Export-CSV $env:userprofile\desktop\export.csv -Append
# A few date/time formats for later use... i hope
$date=(Get-Date -format "yyyy-MM-d")
$time=(Get-Date -format "HH:mm:ss")
$datetime=(Get-Date -format "yyyy-MM-d HH:mm")
$foundProcess = ps $searchString -ea silentlycontinue
if($foundProcess -eq $null) { return; }
$foundprocess | % {
gwmi Win32_Process -Filter ("Handle={0}" -f $_.id ) |
select-Object Name, Handle,
#{Name='Owner'; Expression={$_.GetOwner().User}},
#{Name='Date'; Expression={$date}},
#{Name='Time'; Expression={$time}},
#{Name='DateTime'; Expression={$datetime}},
#{Name='Type'; Expression={''}}
}
}