Skip to content

Add $Now to the automatic variables #24079

Description

@iRon7

Summary of the new feature / enhancement

PowerShell's expression - and argument parsing modes generally results in a need syntax but could also overwhelm your script with Parentheses, Braces and Square Brackets. Wherever I can lose some of them, it would make my script more readable...

Get-Date is a cmdlet that pushes the parser in argument mode where it often is used as a current time variable in an expression.
Meaning it requires to use Parentheses (()) to begin a new expression:

$Start = Get-Date
# Do some things
Write-Debug "Elapsed time: $((Get-Date) - $Start)"

Or a subexpression ($()) when used e.g. in a string:

if ([datetime]::IsLeapYear($(Get-Date).Year)) { Write-Host "$((Get-Date).Year) is a leap year" }

Proposed technical implementation details (optional)

Specifically for the getting the current DateTime additional parenthesis could be avoided if there would exist a $Now in the list of automatic variables.
Wishful thinking:

$Start = $Now
# Do some things
Write-Debug "Elapsed time: $($Now - $Start)"
if ([datetime]::IsLeapYear($Now.Year)) { Write-Host "$($Now.Year) is a leap year" }

Update based on Ryan Yates (@kilasuit)'s referral and other comments below:

I was under the impression that automatic variables could be simply overruled but this is apparently wrong.

Maybe the term "automatic variable" doesn't apply here as usually automatic variables can't be overwritten but if there would exists a common and standard $Now as described here:

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

I might do things along with:

if ([datetime]::IsLeapYear($Now.Year)) { Write-Host "$($Now.Year) is a leap year" }
2024 is a leap year

caveats

  • The variable should be overwritable (similar as putting the definition in my profile) to prevent any break changes.
    • I might of cause put this $Now definition in my own profile but that would not make it common (meaning that I have to redefine it in my shared scripts).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugResolution-No ActivityIssue has had no activity for 6 months or more

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions