PowerShell Date and Time Tip

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.

Capture

$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.

Capture

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(“/”, “-”)

Capture

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”

Capture

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

Capture

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 –

Capture

$time = $time.Tostring().Replace(” “,””)

Removing spaces from the time.

Capture

Now we can use it as desired , see below example  of log file..

$log1 = “.\” + “Powershell_” + $date +  “_” + $time  + “_.log”

Capture

Similarly, if we want to use Month & Year , here is what can be done.

Scary-wall-clock-GIF

#########################Month#######################

$month = get-date

$month = $month.month

Capture

##########################Year########################

$year = get-date

$year = $year.year

Capture

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 

Capture

$lastday = ((Get-Date -day 01).AddMonths(1)).AddDays(-1)

Capture

Now lets check how to get the Midnight

$midnight = get-date -hour 0 -minute 0 -second 0

Capture

These all are the options that We  Scripters mostly use in our scripts to do magic with date/time variables of powershell.

 

Tech Wizard

https://techwizard.cloud

https://syscloudpro.com/

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s