≡ Menu

Powershell: Create a variable to always show current time

We all know that it is easy to get date time using powershell. It is as simple as

$currenttime = Get-date

write-host $currenttime

But the real challenge comes when you want the variable to hold current time whenever we query it. In the above example if you query the value of $currenttime it will show the time when it got the value from get-date. That means it is just holding one instance which is not valid if you want it to hold always currect time.

Today I came across a little PS tip which helps us to do this. That means we can have a dynamic variable which always returns the latest time when queries.

$global:currenttime= Set-PSBreakpoint -Variable currenttime -Mode Read -Action { $global:currenttime= Get-Date }

write-host $currenttime

start-sleep 5

write-host $currenttime

start-sleep 5

write-host $currenttime

 

After executing the above code, you will see output similar to this.

Hope this little tip helps you…

Comments on this entry are closed.

  • asdf May 26, 2015, 2:50 am

    that outputs the date-time not the time.

    • TechiBee May 26, 2015, 8:12 pm

      Hi, yes, it shows date & time.

  • Arunas June 15, 2017, 6:58 pm

    Thanks a lot. One of the best tips I have seen in awhile.