Vippy
Vippy

Reputation: 1422

PowerShell: Refreshing date stored in a variable

I have the following variable that is used in many of my scripts for logging:

$uDate = get-date -format "ddd MM/dd/yyyy HH:mm:ss"

Only problem is that the date is never refreshed and only shows the date/time when the variable was declared.

Upvotes: 2

Views: 8102

Answers (5)

iRon
iRon

Reputation: 23663

Related: #24079 Add $Now to the automatic variables.

You might create a class without (visible) properties and use the ToString method for this:

Class uDateClass {
    [string]ToString() {
        return get-date -format "ddd MM/dd/yyyy HH:mm:ss"
    }
}
$uDate = [uDateClass]::new()
$uDate
Wed 07/24/2024 21:22:47

The disadvantage of this approach apposed to the accepted answer is that it returns a [string] rather than a [DateTime] object, meaning you can't use the DateTime properties and methods as in: $Now.Year.

Upvotes: 0

latkin
latkin

Reputation: 16792

This should not be done with a variable. Variables should store data, not take actions. So the right way to do this is to create a function that returns the current date in the format you want.

But... if you want to get really hack-tastic you can do this by setting a breakpoint on all reads to your variable. The -Action of the breakpoint will reset the value of the variable to the current time.

$rightNow = Get-Date
$null = 
  Set-PSBreakpoint -Variable rightNow -Mode Read -Action { 
    Set-Variable -Scope 1 -Name rightNow -Value (Get-Date) 
  }

Testing...

PS > $rightnow

Monday, August 20, 2012 11:46:04 AM

PS > $rightnow

Monday, August 20, 2012 11:46:09 AM

Upvotes: 6

Zach Bonham
Zach Bonham

Reputation: 6827

Without knowing more, maybe declare a newly defined function "now"?

function now()
{ 
  get-date -format "ddd MM/dd/yyyy HH:mm:ss"
}

Or even using .NET APIs directly:

[datetime]::Now.ToString("ddd MM/dd/yyyy HH:mm:ss")

Upvotes: 6

Greg Wojan
Greg Wojan

Reputation: 772

There is a method to automatically update a variable on each use. Check out New-TiedVariable at PoshCode. Joel Bennett continues to impress. :-) It has its limitations, which are documented, but does work quite nicely.

Basically it's just a function wrapped around the answer provided by @latkin.

Upvotes: 1

EBGreen
EBGreen

Reputation: 37730

Greg Wojan is right that to give you the best answer, we need to know what you are really trying to accomplish. I assume that you want a variable that will magically update itself every time that you try to use it. As far as I know, that isn't possible in PS. The closest I could think of would be to do something like this:

$uDate = {get-date -format "ddd MM/dd/yyyy HH:mm:ss"}
"The date now is $($uDate.Invoke())"
Start-Sleep -Seconds 30
"And now it is $($uDate.Invoke())"

Upvotes: 1

Related Questions