FAQs: Time Stamps, Date Differentials, and Finding an Entry in an Arrray with PowerShell
John Savill's Frequently Asked Questions
October 9, 2017
Three times a week (Monday/Wednesday/Friday), John Savill tackles your most pressing IT questions.
Read through the FAQ archives, or send him your questions via email.
This week we look at a few FAQs related to PowerShell.
Q. How can I convert a string to a time stamp in PowerShell?
Q. How can I easily tell the difference between dates in PowerShell?
Q. How can I find where an entry in an array is located with PowerShell?
----------
Q. How can I convert a string to a time stamp in PowerShell?
Dept - PowerShell
A. It's very simple to convert from a string to a date using the [datetime]::ParseExact command. You tell the command the date format of date in the string which will then convert to a datetime object which can then be manipulated as such.
For example I had string as follows:
$stringdate = "2017-09-29 03:00:18.55014"
Notice in my example it also has millisecond which I don't want in my convert so I trim and only take the first part ignoring the millisecond.
$date = [datetime]::ParseExact($stringdate.Substring(0,19),'yyyy-MM-dd HH:mm:ss',$null)
For example:
PS C:> $stringdate = "2017-09-29 03:00:18.55014"
PS C:> $date = [datetime]::ParseExact($stringdate.Substring(0,19),'yyyy-MM-dd HH:mm:ss',$null)
PS C:> $date
Friday, September 29, 2017 3:00:18 AM
Q. How can I easily tell the difference between dates in PowerShell?
Dept - PowerShell
A. Using New-TimeSpan you can find the difference between two dates and then can even extract out the result in terms of days, hours or whatever you want.
For example here this shows number of days between two days.
(New-TimeSpan -Start $startDate -End $endDate).TotalDays
Q. How can I find where an entry in an array is located with PowerShell?
Dept - PowerShell
A. If you have an array of values its easy to find where in the array a certain value is using the [array]::IndexOf . For example:
PS C:> $strings = "one","two","three","four","five"
PS C:> [array]::IndexOf($strings,"three")
2
Notice the response is 2 (since it starts at 0).
About the Author
You May Also Like