PowerShell Security Log - security

I am writing a PowerShell Script that counts the number of 4624 EventIDs in a given day, but I am getting lost when I go to group the information by date. Is there anyone who could help me out? My output should have the date and the number of Logins for that day and nothing more.
Here is my Code:
Get-EventLog "Security" -Before ([DateTime]::Now) |
Where -FilterScript {$_.EventID -eq 4624}

Try this:
Get-EventLog Security -Before ([DateTime]::Now) |
Where {$_.EventID -eq 4624} |
Group #{e={$_.TimeGenerated.Date}} |
Sort Count -desc
The Group-Object command allows you to specify an expression for the property to group on. In this case you want to group on the date part of the DateTime. Also note that it is unnecessary to quote arguments unless they contain space or special characters like ;, #, {, $ and (.

Related

Powershell: How to get the location of a file, depending on its name?

So my task is to write a PS script, that outputs the location of a database file. The location of the file is:
C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\Mailbox database Name\Mailbox database Name.edb
I figured I can get the name of my Exchange database with
Get-MailboxDatabase | fl Name
which has the output:
Mailbox Database 0161713049
which is the name of the db but there is a bunch of invisible characters before and after the actual name.
So my question is, how could I get rid of these invisible characters? I want to concat a string to make it look like this:
C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\Mailbox Database 0161713049\Mailbox Database 0161713049.edb
I would need this code to work on servers with completely different database names too, so simply removing the unwanted characters from the start with .Remove() may help, but since I don't know for sure the length of the name of the database, I can't remove the characters at the end.
Also I can't get rid of the feeling that there is a much simpler way to get the location of my .edb file.
Powershell treats almost all outputs as an object with properties in hashtable format like #{Name=MYEXCHDB}. When you just want a property value as a string instead, you must expand it like #AdminOfThings suggests:
Get-MailboxDatabase | Select-Object -ExpandProperty Name
To concatenate the name into a string:
$myString = "C:\path\to\$(Get-MailboxDatabase | Select-Object -ExpandProperty Name)"
And as #mathias-r-jessen suggests, the path to the database is another property you can get directly:
Get-MailboxDatabase | Select-Object -ExpandProperty EdbFilePath | Select-Object -ExpandProperty PathName

Trying to Export a CSV list of users using Active Directory Module for Windows Powershell

So the below is where I'm at so far:
import-module activedirectory
$domain = "ourdomain"
Get-ADUser -Filter {enabled -eq $true} -Properties whenCreated,EmailAddress,CanonicalName |
select-object Name,EmailAddress,CanonicalName,whenCreated | export-csv C:\Data\test.csv
Unfortunately, when I run the above I get dates in two different formats in the CSV, e.g.:
01/01/2017
1/01/2017 8:35:56 PM
The issue this poses is that there isn't really a clean way to sort them. Excel's formatting doesn't change either of these formats to be more like the other, both because of the inclusion of time in one and not the other, and because the time-inclusive format doesn't use trailing zeroes in the single digit numbers, but the time-exclusive format does.
We have an existing script that captures users using the LastLogonTimestamp attribute that does this correctly by changing the bottom line to the following:
select-object Name,EmailAddress,CanonicalName,#{Name="Timestamp"; Expression={[DateTime]::FromFileTime($_.whenCreated).ToString('yyyy-MM-dd_hh:mm:ss')}}
For some reason this expression runs properly when we query the LastLogonTimestamp attribute, but when we run this version querying the whenCreated attribute, we get an entirely blank column underneath the Timestamp header.
I'm not particularly knowledgeable about PowerShell itself, and my colleague who had found the original script for the LastLogonTimestamp just found it online and adapted it as minimally as possible to have it work for us, so I don't know if something in this line would work properly with one of these attributes and not the other. It seems strange to me though that two attributes using dates in the same program would store them in different formats though, so I'm not convinced that's it.
In any case, any help anyone can offer to help us get a uniform date format in the output of this script would be greatly appreciated - it needn't have the time included if it's easier to do away with it, though if they're equally easy we may as well keep it.
whencreated is already a [DateTime]. Notice the difference between the properties when you run something like this:
Get-ADUser TestUser -Properties lastlogon,whenCreated | select lastlogon,whenCreated | fl
(Get-ADUser TestUser -Properties lastlogon).lastlogon | gm
(Get-ADUser TestUser -Properties whenCreated).whenCreated | gm
This means that you don't have to convert to a DateTime before running the toString() method.
select-object #{Name="Timestamp"; Expression={$_.whenCreated.ToString('yyyy-MM-dd_hh:mm:ss')}}

Use Powershell to extract remainder of line after certain text

I have a text file with headlines from a LexisNexis Search. I would like to extract the headline from each entry, which comes after the string "HEADLINE: " in the file, and append it to another text file using PowerShell. I am using this line:
select-string -path "C:\Users\WGA\Documents\Personal\ANTH_5330\Content_Analysis\Newspaper_Stories,_Combined_Papers2016-04-18_17-59.txt" -Pattern "HEADLINE: " | select line | out-file C:\Users\WGA\Documents\Personal\ANTH_5330\Content_Analysis\Headlines.txt -append
It is sort of working and I am looking to improve the output. I am linking to the two files below (One is the file to be searched, the other is the output):
https://drive.google.com/folderview?id=0Byxg512qAqFgU0JrRTNUbVlkeGs&usp=sharing
I am open to suggestions to improve this output as, ideally, I would like one line per headline only in the output file.
Let use the regex a little more to get exactly what we want and nothing more. Select-String returns match info objects that contain much of the information you are looking for, including capture groups. Knowing the object properties certain helps. I am assuming you have PowerShell 2.0 for this so it is a little more verbose but works just as well.
$path = "D:\Downloads\Newspaper_Stories,_Combined_Papers2016-04-18_17-59.TXT"
Get-Content $path | Out-String | Select-String -Pattern "(?smi)HeadLine: (.*?)`r`n`r`n" -AllMatches |
Select-Object -ExpandProperty Matches |
ForEach-Object{$_.Groups[1]} |
ForEach-Object{$_.Value -replace "`r`n"," "} |
Set-Content $outputFile
We read in the file as one large string. That is what Out-String is for. We do that since some of your headlines take up multiple lines. Find every line that has "headline" and then grab everything after the colon space up until the first set of newlines. The text we are looking for is inside the capture group (.*?). Next we have to expand the matches objects to get into the groups. Using for each we get the second group which contains our captured group text. A second for each replaces all the newlines with spaces so that the headlines appear as one line in the output.
I noticed that your output file had extra spaces. That is because the default encoding of Out-File is Unicode. Using Set-Content means you won't have to worry about that.
Another thing. If I am wrong and you prefer what you have you can at least skip the header of your output file by changing the select statement to use -ExpandProperty
Sample Output
Charter Schools Fall Short In Public Schools Matchup
State's charter schools buck trend Students at the 108 charters in Colorado have scored higher on state assessment tests than their peers in traditional public schools.
Bills would bypass districts to create charter schools
EDITORIAL The reality of charter schools
EDITORIAL Learning more about charters As Colorado and the nation gain more experience with charter schools, we're discovering that results are mixed-- not unlike public schools.
SPEAK OUT;2 studies, 2 views of charter schools
... output truncated.
try this
Get-Content c:\temp\stories.txt | ? {$_.startswith('HEADLINE: ')} | % {$_.substring(10)} | Out-File c:\temp\headlines.txt -enc ascii

replace string if you dont' know rest of string in PowerShell

Please help. Trying to figure out how to replace a string in PowerShell, but don't know the rest of the string. I have this:
(Get-Content $file) -replace[regex]::Escape('file='*''),('file='+$_.BaseName) | Set-Content $file
I don't know what comes after file=
I tried my code, but it replaces it multiple times instead of just once.
So trying to replace file=* with filename=$_.BaseName.
Thanks for looking.
Just an FYI for anyone using the latest version of PowerShell Community Extensions (http://pscx.codeplex.com), there is a new command called Edit-File that handles this sort of thing nicely (works hard to preserve the file's original encoding):
Get-Item test.txt | Foreach {$bn=$_.BaseName; $_} |
Edit-File -Pattern '(file=).*' -Replace "`${1}$bn"
In theory I shouldn't need the Foreach stage but it seems I've found a limitation in how -PipelineVariable does not work with parameters that aren't pipeline bound. Hmm, add that to the Pscx backlog.

How can I filter Submitted list by multiple user in Perforce?

How can I filter the "Submitted" view by multiple users in perforce?
I want to just see only a few(4-5?) people in the "Submitted" view.
There is a filter function, but filter doesn't take multiple users.
So, can I specify multiple users in the "Submitted" view at perforce?
You are right, there doesn't seem to be a way to accomplish this in either p4v (the GUI) or p4 (CLI). Your best bet is to pass this as a feature request to the excellent perforce support.
I have created a power shell script that could be helpful.
It filters for a specific user, date and you can chose the last number of entries you want to search within (this accelerates the command return).
The result is shown in a power shell grid window which helps you to sort the result entries.
Please feel free to modify variables for your requirements:
$date1 = Get-Date -UFormat "%Y/%m/%d" #today
#$date1 = "2013/09/11" #other day
$users = "user1|user2|user3"
$title = "Submitted changes on: "+$date1+" and users: "+$users
$maxLines = 100
Write-host -foregroundcolor 'cyan' $title
$out = (p4 changes -t -s submitted -m 512 | select-string -Pattern $users | select-string -Pattern $date1)
$out | Select-Object LineNumber,Line,Matches | Out-GridView -Title $title -PassThru
Ihsan
Ok... Just my two cents:
I wanted to filter the submitted list to avoid changelists from other projects on the same P4 server. I tried to filter by user at first, but no luck, just like you.
But! I finally achieved what I wanted by filtering by file path. That way, only my project is visible. I find this quite usefull, as it will show any activity from someone I didn't expect on my project. It's event better than filtering by name. In ma specific case at least.
It doesn't answer the question directly, but it fix the problem I did face :)
Pipe the output to another filter such as grep. For example,
p4 changes -s submitted | egrep "^[^#]* (tom|dick|harry)#"
You may need to modify the regular expression to suit your output format. The ^[^#]* prevents false positives such as tom# in the summary.

Resources