Get-WinEvent Script - powershell

I have a powershell script which is working as expected. I need some help with formatting the output.
$Date = (Get-Date).AddDays(-1)
Get-ChildItem –Path "D:\Log\" -Recurse | Where-Object {($_.LastWriteTime -lt $Date)} | Remove-Item
$filter = #{
LogName='Application'
StartTime=$Date
}
Get-WinEvent -FilterHashtable $filter | Select-Object TimeCreated,Message |
Where-Object { $_.Message -like '*renamed*' -and $_.Message -notlike "*csv*" } |
Out-File -FilePath D:\Log\DailyReport_$(get-date -Format yyyyddmm_hhmmtt).txt
The output is
TimeCreated Message
----------- -------
4/16/2020 4:03:30 AM 04712: renamed
I need the output to be
Date Time,File Name
4/16/2020 4:03:30 AM, 04712: renamed
The column header needs to be renamed with a comma. Any help will be greatly appreciated.
Thanks,
Arnab

You can rename the properties with Select-Object and convert to comma-separated values with ConvertTo-Csv or Export-Csv:
# ...
Get-WinEvent -FilterHashtable $filter |
Select-Object TimeCreated,Message |
Where-Object { $_.Message -like '*renamed*' -and $_.Message -notlike "*csv*" } |
Select-Object #{Name='Date Time';Expression='TimeCreated'},#{Name='File Name';Expression='Message'} |
Export-Csv D:\Log\DailyReport_$(get-date -Format yyyyddmm_hhmmtt).txt -NoTypeInformation

Related

Filter file "yyyy-MM-dd_HH-mm-ss_Computername_Username_File.json" by Computername/Username

I have a folder containing text-files with a standardized naming-scheme like:
2021-03-16_21-25-55_Client1_Edward.Hall_ServerResponse.json
2021-03-16_21-25-33_Client2_Eloise.Glover_ServerResponse.json
2021-03-16_21-17-38_Client3_Millie.Walsh_ServerResponse.json
2021-03-16_21-17-30_Client4_Lilly.Morton_ServerResponse.json
2021-03-16_21-15-45_Client5_Tia.Curtis_ServerResponse.json
2021-03-16_21-15-23_Client1_Edward.Hall_ServerResponse.json
2021-03-16_21-15-10_Client1_Lilly.Morton_ServerResponse.json
2021-03-16_21-15-03_Client2_Eloise.Glover_ServerResponse.json
2021-03-16_21-12-14_Client2_Eloise.Glover_ServerResponse.json
2021-03-16_21-11-25_Client3_Administrator_ServerResponse.json
I want to filter the files and retrieve the latest file (LastWriteTime) of a specific Computername-/Username-combination. Therefore I want to use a code like this:
# $env:COMPUTERNAME = "Client1"
# $env:USERNAME = "Edward.Hall"
$MyFolder = "C:\MyFolder"
Get-ChildItem -Path $MyFolder -File -ErrorAction SilentlyContinue | Where-Object {
$_.Extension -eq ".json" -and $_.COMPUTERNAME -eq $env:COMPUTERNAME -and $_.USERNAME -eq $env:USERNAME
} | Sort-Object -Descending -Property LastWriteTime | Select-Object -First 1
Of course the part -and $_.COMPUTERNAME -eq $env:COMPUTERNAME -and $_.USERNAME -eq $env:USERNAME is NOT working and should only show up the direction to what I imagine.
In the example above the result should be the file "2021-03-16_21-25-55_Client1_Edward.Hall_ServerResponse.json".
I was thinking of using -match, but it should be a exact match -eq.
Could you please help me to find a solution for this?
Thank you very much!
As long as you can count on the name format always conforming to that standard you can just split up the name strings for your required sections:
# $env:COMPUTERNAME = "Client1"
# $env:USERNAME = "Edward.Hall"
$MyFolder = "C:\MyFolder"
Get-ChildItem -Path $MyFolder -File -ErrorAction SilentlyContinue | Where-Object {
($_.Extension -eq ".json") -and ($_.Name.Split('_')[2] -eq $env:COMPUTERNAME) -and ($_.Name.Split('_')[3] -match $env:USERNAME)
} | Sort-Object -Descending -Property LastWriteTime | Select-Object -First 1

Output running services to csv with computer name

I need to generate a csv containing running services to csv with the corresponding computer name
I know there is a simple way to do this and I have been tinkering with creating a new psobject, but I am not sure how to pipe the results to the new-object...
Here is what I am using:
$Input = "SomePath"
$Output = "SomeOtherPath"
$CompNames = Get-Content -Path "$Input"
ForEach ($CompName in $CompNames){
Get-Service -ComputerName $CompName | Where-Object {$_.Status -eq "Running"} | Export-csv -Path "$Output"
}
What I need in the CSV is:
ComputerName, ServiceName, DisplayName
basically, I need to add the computer name to the array.
If you want to be able to pipe the results, use a foreach-object.
$Output = "SomeOtherPath"
Get-Content -Path "SomePath" | ForEach-Object {
Get-Service -ComputerName $_ | Where-Object {$_.Status -eq "Running"} | Select-Object ComputerName, ServiceName, DisplayName
} | Export-csv -Path "$Output"
If you want to stick to a foreach statement, collect it all first then export it.
$Output = "SomeOtherPath"
$CompNames = Get-Content -Path "SomePath"
$results = ForEach ($CompName in $CompNames){
Get-Service -ComputerName $CompName | Where-Object {$_.Status -eq "Running"} | Select-Object ComputerName, ServiceName, DisplayName
}
$results | Export-csv -Path "$Output"
Try like this (Don't use $Input as variable name)
$InputX = "SomePath"
$Output = "SomeOtherPath"
$CompNames = Get-Content -Path "$Input"
ForEach ($CompName in $CompNames){
Get-Service -ComputerName $CompName | Where-Object {$_.Status -eq "Running"} | Select-Object ComputerName, ServiceName, DisplayName | Export-csv -Path "$Output"
}

Getting effective user Permissions for many directories

Usually $Plist would be an array but for example we take just one directory.
My problem is I can't use the $ids var. Somehow I cant read out the data and can't bypass it to:
Get-ADGroup -Identity $id -Properties member | Select-Object -ExpandProperty member
I need the usernames per directory with their group names.
Like : Path GroupName UserList
Can someone help? Maybe tweak my code or make something similar :)
$plist = "\\Server\Share"
$FList = foreach($dir in $Plist)
{
Resolve-Path -Path $dir
Get-Acl -Path $dir -Filter Access | Select-Object -ExpandProperty Access | Where-Object {$_.IdentityReference -like "Domain\*"} | Select-Object IdentityReference
Get-Item $dir | select FullName
}
$Flist | ft FullName, IdentityReference
$identity = $Flist.IdentityReference | out-string
$ids = foreach($ident in $identity)
{
$ident = $ident.Replace("Domain\","")
$ident
}
foreach($id in $ids)
{
$id
Get-ADGroup -Identity $id -Properties member | Select-Object -ExpandProperty member
}
Do not use ft (Format-Table) or Out-String on values that you may ned later in your script.
$ids = foreach($ident in $Flist.IdentityReference){
"$ident".Replace('Domain\','')
}
You could also strip the domain prefix from all the user names in one go with the -replace operator:
foreach($id in $flist.IdentityReference.Value -replace 'Domain\\')
{
Get-ADGroup $id -Properties member | Select-Object -ExpandProperty member
}
The Final Script is this, for people who might need something similar. So you can read out the effective permissions and show the group member of permission granted groups.
$ErrorActionPreference = "SilentlyContinue"
$Path = "\\Server\Share\Logs\"
$Log = $Path + "Effective_Permissions" + ".log"
$PPath = Read-Host "Enter Path to scan"
$plist = Get-Childitem -Path $PPath -Recurse | ?{ $_.PSIsContainer } | Select-Object FullName
foreach($Dir in $PList)
{
$Dir = $Dir -replace "#{FullName=", "" -replace "}"
Resolve-Path -Path $Dir
Write-Output "`n" | Out-File $log -append
Write-Output "#######################################################################" | Out-File $Log -append
Get-Item $Dir | select FullName | Out-File $Log -append
$AclList = Get-Acl -Path $Dir -Filter Access | Select-Object -ExpandProperty Access | Where-Object {$_.IdentityReference -like "Domain\*"} | Select-Object IdentityReference
Get-Acl -Path $dir -Filter Access | Select-Object -ExpandProperty Access | Where-Object {$_.IdentityReference -like "Domain\*"} | Out-File $Log -append
foreach($Id in $AclList.IdentityReference.Value -replace 'Domain\\')
{
$ADGroup = Get-ADGroup $Id -Properties member | Select-Object -ExpandProperty member
Write-Output "`n" | Out-File $Log -append
Write-Output "Member of $Id `n
---------------------------------" | Out-File $Log -append
foreach ($Object in $ADGroup)
{
$Group = Get-ADUser -filter * -SearchBase "$Object"
if($Group -ne $null)
{
$GrName = $Group.Name
Write-Output "$GrName" | Out-File $Log -append
}
}
}
Clear-Variable Object, Group, ADGroup, ACLList, GRName, Id
}

PowerCLI Get VMs those fit some conditions

I'm trying to get our some Linux distros from vCenter by using PowerCLI. But I don't want to get Appliance VMs. So I have 2 different successful PowerCLI scripts those can find these machines. I want merge these scripts but I'm new on PowerCLI and it's syntax.
I'm sharing these scripts at below:
Non-Appliance List:
Get-VM | `
Get-Annotation | `
Where-Object {$_.name -eq "Appliance"} | `
Where-Object {$_.value -eq 'No'} | `
Export-Csv C:\Users\me\Documents\non-appliance-list.csv -NoTypeInformation -UseCulture
Linux List:
Get-View -Property #("Name", "Config.GuestFullName","Guest.GuestFullName") | `
Select -Property Name, #{N="COS";E={$_.Config.GuestFullName}}, #{N="ROS";E={$_.Guest.GuestFullName}} | `
Where-Object ({$_.ROS -like 'Centos*' -or $_.ROS -like 'Suse*' -or $_.ROS -like 'Ubuntu*'}) | `
Select AnnotatedEntity,Name,Value | `
Export-Csv C:\Users\me\Documents\linux-list.csv -NoTypeInformation -UseCulture
Script I imagined but doesn't worked:
Get-VM | `
Get-Annotation | `
Where-Object {$_.name -eq "Appliance"} | `
Where-Object {$_.value -eq 'No'} | `
Get-View -Property #("Name", "Config.GuestFullName","Guest.GuestFullName") | `
Select -Property Name, #{N="COS";E={$_.Config.GuestFullName}}, #{N="ROS";E={$_.Guest.GuestFullName}} | `
Where-Object ({$_.ROS -like 'Centos*' -or $_.ROS -like 'Suse*' -or $_.ROS -like 'Ubuntu*'}) | `
Select AnnotatedEntity,Name,Value | `
Export-Csv C:\Users\me\Documents\linux--list.csv -NoTypeInformation -UseCulture
Maybe It has been a XY-Question. If you have a better way to get Linux VMs those are not appliance, you can say me this method.
You might be better off making use of some variables along the way to help make this a bit easier.
Example:
$LinuxVMs = Get-VM | `
Get-Annotation | `
Where-Object {$_.name -eq "Appliance"} | `
Where-Object {$_.value -eq 'No'}
Now you have the ability to pipeline the LinuxVMs variable into the Export-Csv cmdlet if you need as well as reference it for your second script.
Example:
$LinuxVMs | Get-View -Property #("Name", "Config.GuestFullName","Guest.GuestFullName") | `
Select -Property Name, #{N="COS";E={$_.Config.GuestFullName}}, #{N="ROS";E={$_.Guest.GuestFullName}} | `
Where-Object ({$_.ROS -like 'Centos*' -or $_.ROS -like 'Suse*' -or $_.ROS -like 'Ubuntu*'}) | `
Select AnnotatedEntity,Name,Value | `
Export-Csv C:\Users\me\Documents\linux-list.csv -NoTypeInformation -UseCulture
You have just mashed the scripts together, piping the first into the second.
This won't work.
You can have each script block in a single script, then merge the resulting csv's using one of the methods here:
Merging multiple CSV files into one using PowerShell
Stinkyfriend's code:
Get-ChildItem -Filter *.csv | Select-Object -ExpandProperty FullName | Import-Csv | Export-Csv .\merged\merged.csv -NoTypeInformation -Append

powershell - getting last users last login from local server

I have been working on a script to show the the last login of each of the users that have been logging into their terminal server.
The script works if they are not on a domain but when they are on a domain, it would show users that have not logged into that particular server.
Is there a way for me to edit the script to where it only shows users that have logged into that specific server?
Here is the code:
#This script will check which users have logged on in the last X days
#Set Variables
#Change the number in the parenthesis after adddays to change how far back
to filter
#example (get-date).adddays(-30) gets all logins for the last 30 days from
today (-60) would be the last 60 days
$AuditDate = Get-Date (get-date).adddays(-30) -format "MM/dd/yyyy h:mm:ss
tt"
$ComputerName = $env:COMPUTERNAME
$CurrentDate = Get-Date -UFormat "%Y-%m-%d"
#Delete any previously created files
Get-ChildItem -Path "C:\PowerShellScripts\LastLogon\Results" -Recurse |
Where-Object CreationTime -lt (Get-Date).AddDays(-0) | Remove-Item -
ErrorAction SilentlyContinue
#The Login Profile is filtered here
Get-WmiObject -class Win32_NetworkLoginProfile -ComputerName $ComputerName|
#Where-Object -FilterScript {$_.LogonServer -like $ComputerName}|
Where-Object -FilterScript {$_.FullName -notlike "*Agvance*"} |
Where-Object -FilterScript {$_.FullName -notlike "*Sophos*"} |
Where-Object -FilterScript {$_.FullName -ne "AgvAdmin"} |
Where-Object -FilterScript {$_.FullName -ne ""} |
Where-Object {$_.Name -notlike "*ssi1*"}|
Where-Object {$_.Name -notlike "*ssi2*"}|
Where-Object {$_.Name -notlike "*ssi3*"}|
Where-Object {$_.Name -notlike "*ssi4*"}|
Where-Object {$_.Name -notlike "*ssi5*"}|
Where-Object {$_.Name -notlike "*ssi6*"}|
Where-Object {$_.Name -notlike "*ssi7*"}|
Where-Object {$_.Name -notlike "*ssi8*"}|
Where-Object {$_.Name -notlike "*ssi9*"}|
Where-Object {$_.Name -notlike "*ssiadmin*"}|
Where-Object -FilterScript {$_.Name -notlike "*SYSTEM*"} |
Where-Object -FilterScript {$_.Name -notlike "*SERVICE*"} |
Where-Object -FilterScript {!
[System.String]::IsNullOrWhiteSpace($_.LastLogon)} |
Where-Object -FilterScript {$_.ConvertToDateTime($_.LastLogon) -ge
$AuditDate} |
Select-Object Name,LogonServer,#{label='LastLogon';expression=
{$_.ConvertToDateTime($_.LastLogon)}} -ErrorAction SilentlyContinue | sort-
object Name | Export-Csv
C:\PowerShellScripts\Lastlogon\Results\LastLogon.csv -NoTypeInformation
#Extra filter to filter out SSI users
#Import-Csv C:\PowerShellScripts\Results\LastLogon.csv | Where-Object
{$_.Name -notlike "*ssi*"} |Export-Csv
C:\PowerShellScripts\Lastlogon\Results\LastLogon.csv -NoTypeInformation -Force
#The user count is created here
$number = (Import-Csv C:\PowerShellScripts\Lastlogon\Results\LastLogon.csv |
measure | % { $_.Count})
#The file is renamed to include computername, date, and user count
rename-item -path C:\PowerShellScripts\Lastlogon\Results\LastLogon.csv -NewName C:\PowerShellScripts\Lastlogon\Results\LastLogon-$ComputerName-$CurrentDate-UserCount-$number.csv
You can give this a try and see if it provides what you need.
$time = (Get-Date) – (New-TimeSpan -Day 30)
# You can additional filters in ? { $_.Properties[1].Value -ne 'SYSTEM' } by
# modifying it with -and statements
# i.e. ? { ($_.Properties[1].Value -ne 'SYSTEM') -and ($_.Properties[1].Value -ne 'USER')}
Get-WinEvent -FilterHashtable #{Logname='Security';ID=4672;starttime=$time} -ComputerName $ComputerName | ? { $_.Properties[1].Value -ne 'SYSTEM' } | select #{N='User';E={$_.Properties[1].Value}}, #{N='TimeCreated';E={$_.TimeCreated}}