I am struggling a bit with an issue I hope you can help me with.
I am using get-winevent to grab specific events from a computer and export the results to a csv.
I am setting a variable to hold all of the returned events and then using a foreach loop to step through all the events and export them to a csv file.
When I export the timecreated object, the data is formatted as date-time and I can sort oldest to newest or newest to oldest. What I am running into is that the default format of "timecreated" is "MM/DD/YYYY hh:mm ". This causes a problem in that, unless I can see seconds and milliseconds, a lot of these events appear to happen at the same time.
To resolve this, I have been using the following to format the date:
$ticks = [datetime]$event.timecreated.Ticks
$date = $ticks.Tostring("MM/dd/yyyy hh:mm:ss:fff")
This works well when I just output to the screen, the date shows exactly like I want it to. However, since the variable is a string, when I export the variable to excel I can’t sort based on time.
Does anyone know of a way to convert ticks to the display format I want, but keep it as datetime rather than a string? Or any way to grab the timecreated object and format it the way I want, without having to convert it to a string?
I'm beginning to think I may have to create a PSObject and handle it that way, but I am not sure I can do it even then.
Thanks for reading.
if i understand your whole query and excepted result.
I have tested what your are looking for and result it to we doesn't have to add "fff" to string date format on excel because it's doesn't work.
Try this :
$ticks = [datetime]$event.timecreated.Ticks
$date = $ticks.Tostring("MM/dd/yyyy hh:mm:ss")
The full example we have using for testing :
$events =Get-WinEvent -ListLog * | Where {$_.IsClassicLog -eq ‘True’}
$events | Select-Object LogMode, RecordCount, LogName, #{n="DateWrite";e={$_.LastWriteTime.ToString("dd/MM/yyyy hh:mm:ss")}} | Export-Csv -Path c:\fso\event_tester.csv -Encoding ascii -NoTypeInformation
At result have the excepted Date column :
Resources :
How to represent a DateTime in Excel
pandas output timestamps to_excel with microseconds
Related
I'm looking for a bit of assistance here. I currently have a Powershell script which adjusts the dates within a file. I'm looking to stop myself having to manually adjust these dates every time. What I need is to replace the date two days ago, with the date from yesterday.
I believe that I'd have to use (Get-Date).AddDays(-1) and (Get-Date).AddDays(-2) but I'm not exactly sure how I'd script this in!
What I currently have:
echo "Adjusting Import Dates"
(Get-Content D:\Temp\Example.txt).replace('20180917', '20180918') | Set-Content D:\Temp\Example.txt
You could try this:
$yesterday = (Get-Date).AddDays(-1).tostring("yyyyMMdd")
$twodaysago = (Get-Date).AddDays(-2).tostring("yyyyMMdd")
(Get-Content D:\Temp\Example.txt).replace($twodaysago, $yesterday) | Set-Content D:\Temp\Example.txt
You just introduce variables for the two dates and format them to the required date format.
There is probably some other way of replacing in files, but the above should work.
so I've got a CSV file with 5 headings: name, collectionDate, location, equipmentNotes, manager.
Now my collectionDates are all in UK format so DD/MM/YYYY. I only want to import data from the CSV with collection dates that are 7 days or less in the future.
So today is 17/08, therefore I would only want to pull data from the CSV that is dated between 17/08 to 24/08.
Although Powershell sort of handles datetime objects in UK format if you tell it to, I seem to be unable to then manipulate the date to add on 7 days.
Here is my current code:
$today = Get-Date
$thisWeek = $today.AddDays(7)
$thisWeekString = $thisWeek.ToString()
$dateParts = $thisweekString -split " "
$weekFinal = $dateParts[0]
$import = Import-Csv #("\\location\EmailCSV.csv") | Where-Object {$_.collectionDate -lt $weekFinal}
Powershell correctly adds 7 days to the datetime to make it 24/08, and then when converting it to a string and removing the time from it, it correctly sets the variable as 24/08/2018. But when I then go to compare them in the Import cmdlet, it just returns all data in the CSV, rather than dates less than 24/08.
I also know Powershell can compare these, because if I create a separate variable $otherDate with 24/08/2018 in it, and then create an if statement that checks if $weekFinal is greater or less than $otherDate, it correctly runs the statement when true.
I've tried using both Where and Where-Object in the Import-Csv cmdlet, but both have returned the same results.
How do I get Powershell to correctly compare $_.collectionDate and $weekFinal to filter the imported data from the csv?
It is easiest to perform all calculations and comparisons using [datetime] instances - avoid string operations (except for converting a string representation of a date to a [datetime] instance).
First, express today's date and 1 week from now as a [datetime] instance without a time-of-day component:
$today = (Get-Date).Date # Today's date, without a time component (midnight)
$oneWeekFromToday = $today.AddDays(7)
Then use [datetime]::Parse() to convert the invariably string-typed CSV column value of interest to a [datetime] instance so you can perform proper date-comparison.
$import = Import-Csv \\location\EmailCSV.csv | Where-Object {
$thisDate = [datetime]::Parse($_.collectionDate)
# Process this row if its date falls between today and 1 week from now, inclusively.
$thisDate -ge $today -and $thisDate -le $oneWeekFromToday
}
Important: use [datetime]::Parse('...'), not a [datetime] '...' cast, because only [datetime]::Parse() respects the current culture's date and time formats; by design, PowerShell's casts and string interpolation always use the invariant culture, irrespective of the current culture - for more information, see this answer of mine.
Try casting the strings to [datetime] in your comparison. When using a sample set of data, I was able to get the expected results.
$import = Import-Csv #("\\location\EmailCSV.csv") | Where-Object {[datetime]$_.collectionDate -lt [datetime]$weekFinal}
This is the name of my file myregistration_20180105041258_NOTIFICATION_1.zip and 20180105041258 the numbers are a timestamp. I've so many files of this format. These files will be posted to my share path every day. I've automated to download all the files. But I want to download daily files with help of date. Can anyone suggest me how can I do this using power shell???
If I have got this right, then your requirement is to change the numbers(in the file names) which are actually a timestamp, into a datetime format and the use this to download the files or do whatever operation you deem to.
For that, I would use the -split parameter to get the number from the filename and then convert the number into datetime format using the PoSh ParseExact function. The code will look something like this.
$string = " myregistration_20180105041258_NOTIFICATION_1.zip"
$array = #($string.Split('_'))
$datetime = [datetime]::parseexact($array[1], 'yyyyMMddhhmmss', $null)
Now your $datetime variable will contain the date of the corresponding file and you can use this to proceed further. If you have a bunch of files, you can loop through each of them using a foreach loop.
For example:
$original = "myregistration_20180105041258_NOTIFICATION_1.zip";
$trimmed = $original | Select-String -Pattern "myregistration" -InputObject {$_.TrimEnd("whatever you want to trim")}
P.S. It's possible also if you need to get the timestamp only to say:
$original -match "\d" and pull the value of it from $Matches[0].
I have a CSV file with the following data
"Date","Time","Name","SourceIP","DestinationIP"
"Sep 1","03:55:57","mmt-5","172.16.48.158","22.22.22.22"
"Sep 1","03:55:57","mmt-5","172.16.48.158","22.22.22.22"
"Sep 1","03:55:57","mmt-5","172.16.48.158","22.22.22.22"
"Sep 1","03:55:57","mmt-5","172.16.48.158","22.22.22.22"
I would like to convert the date into something more usable like 09-01-2016 (the year would be the current year).
How can I accomplish this?
That's easy using the [DateTime] class's ParseExact method. You supply the string that is a date, you tell it how the date is formatted, and you provide a culture or provider or something, but I always just use $null.
[datetime]::ParseExact("Sep 1","MMM d",$null)
That comes out to:
Thursday, September 1, 2016 12:00:00 AM
So you could just do something like:
$Array | ForEach{[datetime]::ParseExact($_.Date,"MMM d",$null)}
And that would convert each entry's Date property to a valid [datetime] object. Then you just format it however you want:
$Array | ForEach{[datetime]::ParseExact($_.Date,"MMM d",$null).ToString("M-d-yyyy")}
That would output:
9-1-2016
Or for the exact thing you asked for use "MM-dd-yyyy" to get 09-01-2016.
Edit: Thanks to wOxxOm for educating me about the third parameter's necessity when dealing with non-localized date formats! So, if this needs to be localized for other cultures, you will need to include that last parameter. That can be done as such:
$Culture = [cultureinfo]::GetCultureInfoByIetfLanguageTag('en-US')
$Array | ForEach{[datetime]::ParseExact($_.Date,"MMM d",$Culture).ToString("MM-dd-yyyy")}
Edit2: Ok, to replace your current Date field with this information you could pass the array to the Select command, and create a new Date property on the fly, and discard the original, then pass that to Export-CSV:
$Array | Select *,#{l='Date';e={[datetime]::ParseExact($_.Date,"MMM d",$null).ToString("M-d-yyyy")}} -Exclude Date | Export-CSV D-Sample-2.csv -NoType
I'm attempting to use Active Directory extensionAttributes to keep track of certain dates (like start date, termination date, etc) so that I can trigger certain actions when that date occurs.
I'm having an issue with the different variations that a date can be entered in (M/D/YY, MM/DD/YY, MM/DD/YYYY, etc). For example, I can use Get-Date to output to a format of M/D/YYYY, but I run into issues when someone enters MM/DD/YY.
Is there a way to make this work so that it can accept other variations (as long as it's month/date/year)?
Here are a couple of lines from the script in question. This runs once a day, and checks for new users starting the following day.
$StartingOn = (Get-Date).AddDays(1).ToShortDateString()
$NewUserCheck = Get-QADUser -DontUseDefaultIncludedProperties -IncludedProperties extensionAttribute11 | where { $_.extensionAttribute11 -eq $StartingOn }
Notice how it only returns as long as the date equals the Get-Date output. It was the only way I was able to get this to work properly. Even at that, if someone typed in 07/20/15, the output would return nothing.
Don't try to compare date strings. Use DateTime comparison which won't care about formatting details e.g.:
$StartingOn = (Get-Date).AddDays(1)
$NewUserCheck = Get-QADUser -DontUseDefaultIncludedProperties -IncludedProperties extensionAttribute11 |
Where { [DateTime]($_.extensionAttribute11) -eq $StartingOn}