Today I will provide you Tips on how to use Date/Time in your scripts to create Log files , as well as understanding of the Date/Time function.
$date = get-date
Here is the output of above command but this can’t be used for creating files with time stamps as there are special characters, so you need to utilize format parameter.
$date = get-date -format d
Below is the output you will get after using the format parameter, there are other options nstead of d that can be used for different output styles. I am not detailing the other parameters /options in this blogpost.
Now you have the date in much better format but still slashes “\” are left which we have to remove with -replace
$date = $date.ToString().Replace(“/”, “-”)
This is the format which can now be used in our scripts to create log files, files, csv etc. with time stamps appended.
See Example below, where $date variable has been used to create the log file.
$log1 = “.\” + “Powershell_” + $date + “_.log”
Same way let’s work on time variable and than it can be utilized inside the scripts.
Lets use the format option as before ….
$time = get-date -format t
As you can expect, I will now use -replace so that It can be used for creating files/logs with time stamps.
$time = $time.Tostring().Replace(“:”,”-“)
Replace : with –
$time = $time.Tostring().Replace(” “,””)
Removing spaces from the time.
Now we can use it as desired , see below example of log file..
$log1 = “.\” + “Powershell_” + $date + “_” + $time + “_.log”
Similarly, if we want to use Month & Year , here is what can be done.
#########################Month#######################
$month = get-date
$month = $month.month
##########################Year########################
$year = get-date
$year = $year.year
Now if We want to use first day & last day of the month, here is what you can do to achieve this.
$firstday = get-date -day 01
$lastday = ((Get-Date -day 01).AddMonths(1)).AddDays(-1)
Now lets check how to get the Midnight
$midnight = get-date -hour 0 -minute 0 -second 0
These all are the options that We Scripters mostly use in our scripts to do magic with date/time variables of powershell.
Tech Wizard