Get-EventLog with Append - powershell

So i have this code below that collects the stated EventIDs with the use of append. The problem is have is it only saves to a single file. What i want to do is save the collection to a daily file so i can do a daily report. A little help please?
$endtime = Get-Date
$starttime = (Get-Date).AddHours(-3)
$domain = "ComputerName"
$event = get-eventlog security -ComputerName $domain -after $starttime -before $endtime | where-object {($_.EventID -eq 4724) -or ($_.EventID -eq 4723) -or ($_.EventID -eq 4720)}
$event | select MachineName,EventID,TimeGenerated,Message | export-csv -path "E:\EventLogs\temp.csv"
get-content "E:\EventLogs\temp.csv" | out-File -filepath "E:\EventLogs\AccountAudit.csv" -append -enc ASCII -width 500

Export-Csv Has an -Append Parameter as well, you can shorten your code to:
$event = get-eventlog security -ComputerName $domain -after $starttime -before $endtime |
Where-object {($_.EventID -eq 4724) -or ($_.EventID -eq 4723) -or ($_.EventID -eq 4720)}
$event | select MachineName,EventID,TimeGenerated,Message |
Export-Csv -path "E:\EventLogs\AccountAudit.csv" -Append -Encoding ASCII

Simply add a get-start with some parameters to get a date that's filename friendly (no "/" for example) and save it in a variable. Then replace AccountAudit on the last line with the variable.

Related

powershell hashtable (export-Csv) to CSV

The following code in powershell creates a file with key/value pairs.
$result = #()
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-5)) -InstanceId 4624 |
ForEach-Object {
if ($_.ReplacementStrings[5] -ne "SYSTEM")
{
$result += [PSCustomObject]#{
Time = $_.TimeGenerated
Workstation = $_.ReplacementStrings[11]
}
}
}
#$result | Export-Csv -Path .\Logins.csv -NoTypeInformation
$result | Out-File "C:\Temp\Logins.csv"
The above results in the following file contents:
However, I want the contents in CSV format. If I change the commented lines out as below:
$result = #()
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-5)) -InstanceId 4624 |
ForEach-Object {
if ($_.ReplacementStrings[5] -ne "SYSTEM")
{
$result += [PSCustomObject]#{
Time = $_.TimeGenerated
Workstation = $_.ReplacementStrings[11]
}
}
}
$result | Export-Csv -Path .\Logins.csv -NoTypeInformation
#$result | Out-File "C:\Temp\Logins.csv"
Then I get the following:
Googling around through myriad pages and examples, I (mis?)understand this to be a hashtable and that the Export-Csv should work to create a csv file. I cannot seem to get it to work.
Any help is greatly appreciated.
Hmmm ... the following code works exactly like I'd expect it:
$result =
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-5)) -InstanceId 4624 |
ForEach-Object {
if ($_.ReplacementStrings[5] -ne "SYSTEM") {
[PSCustomObject]#{
Time = $_.TimeGenerated
Workstation = $_.ReplacementStrings[11]
}
}
}
$result | Export-Csv -Path .\Logins.csv -NoTypeInformation
BTW: It is recommended not to use Get-Eventlog anymore. Use Get-WinEvent instead. ;-)
Another option could be just this:
Clear-Host
$result = #()
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-1)) -InstanceId 4624 |
ForEach-Object {
if ($_.ReplacementStrings[5] -ne "SYSTEM")
{
$result += [PSCustomObject]#{
Time = $PSItem.TimeGenerated
Workstation = $PSItem.ReplacementStrings[11]
}
}
}
$result | ConvertTo-Csv -NoTypeInformation | Out-File -FilePath 'Logins.csv'
Get-Content -Path 'Logins.csv'
# Results
<#
"Time","Workstation"
...
"06-Aug-22 16:45:37","-"
"06-Aug-22 16:45:17","-"
"06-Aug-22 16:44:29","-"
...
#>
Update as per my comment.
The results are the same as the above, either to the screen or the file:
Clear-Host
(Get-EventLog -LogName Security -After ((Get-Date).AddDays(-1)) -InstanceId 4624) -ne 'SYSTEM' |
Select-Object -Property #{Name = 'Time';Expression = {$PSItem.TimeGenerated}},
#{Name = 'Workstation';Expression = {$PSItem.ReplacementStrings[11]}} |
Export-Csv -Path 'Logins.csv'
Get-Content -Path 'Logins.csv'

Out-File unnecessary characters

I have the script below which pings a list of machines, outputs the result to CSV and gets the lastlogontimestamp of the machine.
It works fine, except the lastlogontimestamp comes out like this:
CCC-APP01,172.22.100.15,#{lastLogonDate=07/25/2018 13:24:54}
How can I get rid of the extra characters: #{lastlogondate=...}?
$OutputCSV = "C:\TEMP\OUPingResults.csv"
$SearchLocation = "OU=AA,OU=Servers,DC=LocA,DC=XYZ,DC=com"
$Computers = Get-ADComputer -Filter * -SearchBase $SearchLocation |
Select Name |
Sort-Object Name
$Computers = $Computers.Name
$Headers = "ComputerName,IP Address,LastLogonTimeStamp"
$Headers | Out-File -FilePath $OutputCSV -Encoding UTF8
foreach ($computer in $Computers) {
Write-host "Pinging $Computer"
$Test = Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue -ErrorVariable Err
if ($test -ne $null) {
$IP = $Test.IPV4Address.IPAddressToString
$LastLogonTimeStamp = Get-ADComputer $Computer -Prop CN,lastLogonTimestamp |
Select #{n="lastLogonDate";e={[datetime]::FromFileTime($_.lastLogonTimestamp)}}
$Output = "$Computer,$IP,$LastLogonTimeStamp"
$Output | Out-File -FilePath $OutputCSV -Encoding UTF8 -Append
} else {
$Output = "$Computer,$Err"
$Output | Out-File -FilePath $OutputCSV -Encoding UTF8 -Append
}
}
The expression ... |Select-Object #{N='SomeName';E={"SomeValue"}} will produce an object that has a property named SomeName with the value "SomeValue".
What you see in the output is a string representation of this object.
If you want only the value, change the $LastLogonTimeStamp assignment to:
$LastLogonTimeStamp = [datetime]::FromFiletime((Get-ADComputer $Computer -Prop lastLogonTimestamp).lastLogonTimestamp)

Why does this outputting numbers in the file not the machine name?

The file that I'm outputting doesnt contain the $machine and if its valid or not, it contains numbers. How do I get this to output the machine name and if its valid or not?
Import-Module ActiveDirectory
$enddate = Get-Date
$machines=(Get-ADComputer -filter * -SearchBase 'OU=this,OU=is,OU=my,DC=domain,DC=com' -Properties * | Select Name, lastlogondate |Where-Object {$_.LastLogonDate -lt ($enddate).AddMonths(-2)} |Sort lastlogondate).name
foreach ($machine in $machines)
{
if (test-Connection -ComputerName $machine -count 1 -ErrorAction SilentlyContinue)
{
Write-Output "$machine is valid"
}
Write-Output "$machine is not valid" | Export-Csv
c:\machine_not_valid.csv -Append -NoClobber -NoTypeInformation
}
Export-Csv expects an object, not a string. It then uses the properties of this object as headers for the CSV.
It is outputting numbers because it is receiving string as input, which has the single property Length
You also have an error in your code where the "$machine is not valid" part is outside of the if statement and not in an else statement.
If you have multiple values, Export-Csv is the way to go. If you only have one, use Out-Fileas you will not need to create an object:
Import-Module ActiveDirectory
$enddate = Get-Date
$machines=(Get-ADComputer -filter * -SearchBase 'OU=this,OU=is,OU=my,DC=domain,DC=com' -Properties * | Select Name, lastlogondate |Where-Object {$_.LastLogonDate -lt ($enddate).AddMonths(-2)} |Sort lastlogondate).name
foreach ($machine in $machines)
{
if (test-Connection -ComputerName $machine -count 1 -ErrorAction SilentlyContinue)
{
Write-Output "$machine is valid"
}else{
Write-Output "$machine is not valid" | Export-Csv c:\machine_not_valid.csv -Append -NoClobber
}
}

Adding new lines to Existing CSV using powershell?

I wrote a script that would fetch all the services running under an account name.
This part works fine except I want to add results to an existing csv. Add-content is messing up with my format. Please help as i am new here.
script:
$servers = #("a", "b")
$domain = "abc.com"
foreach($server in $servers){
$serverFQDN = $server+"."+"$domain"
Invoke-Command -computername $serverFQDN{
param($server)
Write-host "On" + $server -ForegroundColor Yellow
Get-WMIObject Win32_Service | Where-Object {$_.startname -match "ciqdev*" }
# | where-object {$_.state -eq "running"}
}-argumentlist $server | select pscomputername,caption | export-Csv Z:\RT\myCSV.csv
}
Use -Append :
export-Csv Z:\RT\myCSV.csv -Append

Powershell Security Log Get-EventLog

I am trying to write something up in powershell and completely new to powershell, I need help. What I'm trying to do is get information from the Security Log. Specifically, the last login for users over the last two weeks. The code that I have so far is getting login's for the event ID 4624 based on the last 100 events. This is also returning not just users but computers as well. How can I limit the results to just users over a period of two weeks? Is this even possible?
$eventList = #()
Get-EventLog "Security" -After $Date `
| Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10} `
| foreach-Object {
$row = "" | Select UserName, LoginTime
$row.UserName = $_.ReplacementStrings[5]
$row.LoginTime = $_.TimeGenerated
$eventList += $row
}
$eventList
EDIT: Solved with code
$Date = [DateTime]::Now.AddDays(-14)
$Date.tostring("MM-dd-yyyy"), $env:Computername
$eventList = #()
Get-EventLog "Security" -After $Date `
| Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10 -and $_.ReplacementStrings[5] -notlike "*$"} `
| foreach-Object {
$row = "" | Select UserName, LoginTime
$row.UserName = $_.ReplacementStrings[5]
$row.LoginTime = $_.TimeGenerated
$eventList += $row
}
$eventList
Use -before and -after parameters to filter the log by date. Use get-help get-eventlog -full to see all the parameters.
The users's last logon is stored in Active Directory. Seems like it would be a lot easier to pull it from there than chewing through event logs.
Use PowerShell to search the Active Directory:
Import-Module ActiveDirectory
Get-QADComputer -ComputerRole DomainController | foreach {
(Get-QADUser -Service $_.Name -SamAccountName username).LastLogon.Value
} | Measure-Latest