Home > Mobile >  How to set Get-Date format as variable but get up to date time in function
How to set Get-Date format as variable but get up to date time in function

Time:05-17

I'm trying to store a get-date format as a variable so it's at the top of the file but be able to have it get an up to date get-date in functions using the variable name. Example:

    $LogDir = "c:\somefolders"
    $LogSubDir = $(Get-Date -f MM-yyyy)
    function MakeLogSubDirs{
    $Path = "$LogDir\$LogSubDir" # rather than "$LogDir\$(Get-Date -f MM-yyyy)"
    If(!(test-path $path)) {
        New-Item -ItemType Directory -Path $path
    }

But I don't want it to set the time in the variable, I want the variable in the variable, to get gotten in the function. I tried single quotes $LogSubDir = '$(Get-Date -f MM-yyyy)', but that didn't work. "$LogDir\$(Get-Date -f MM-yyyy)" works to make the folder. Any suggestions?

CodePudding user response:

here is a demo of the save the pattern into a $Var & use that later idea ... [grin]

$EU_Backwards = 'dd-MM-yyyy'
$US_InsideOut = 'MM-dd-yyyy'
$SaneSortable = 'yyyy-MM-dd'

Get-Date -Format $EU_Backwards

output = 15-05-2022


as an aside, try to use the sane, sortable largest 1st layout whenever you can. [grin]

CodePudding user response:

After looking at my script again, really what I'm looking for is TimeStamp, given the way the question is worded, this is the correct answer. In my case specifically, I already have TimeStamp declared, so am looking for a second one but I digress.

filter timestamp {"$(Get-Date -Format MM/dd/yyyy_HH:mm:ss) $_"}

This worked to fully resolve the question

filter timestamp2 {"$(Get-Date -Format MM-yyyy) $_"}
  • Related