Question

For instance, I have several date attributes I'd like to retrieve from a single folder. I'd like to format them in a particular format. I've found a way to do this using Get-Date inside of a calculated property.

PS B:\abrabackups> Get-ItemProperty -Path .\AbraSuite01.03.2014 | select Name,@{Name="CreationTime";Expression={($_.CreationTime | Get-Date -format 'ddd MMM dd yyyy HH:mm:ss') + ' GMT-000' }} | ConvertTo-JSON

However, if I do this for the rest of the date attributes I have to copy and paste the expression of the calculated property several times over:

@{Name=$some_date_attr;Expression={($_.$some_date_attr | Get-Date -format 'ddd MMM dd yyyy HH:mm:ss') + ' GMT-000' }}

If anything changes in the format I have to change it as many times are there are date properties. Is there a way to refactor it into a function that I can pass a date attribute to and have the function return it in the requested format?

Was it helpful?

Solution

This is basic programming. All you do is create a function with an input and have it return a value. I am going to assume that the data type of the date value is a DateTime or castable as one.

function MyDateFormat([DateTime]$date) {
    return (Get-Date $date -format 'ddd MMM dd yyyy HH:mm:ss') + ' GMT-000'
}

(Please choose a better name, of course. This is only an example.) Then call your function instead:

@{Name=$some_date_attr;Expression=(MyDateFormat $_.some_date_attr)}

If you really want it in GMT, you may want to make sure it's actually using a UTC time.

OTHER TIPS

Function Format-Date{
    Param([DateTime]$InputDate)
    (Get-Date $InputDate -format 'ddd MMM dd yyyy HH:mm:ss') + ' GMT-000'
}

Then just throw a date object at that, or a string in a date format ("1/13/14" or "2/14/14 21:12:47") and it spits back your desired format. You could name the function something shorter for ease of use of coarse.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top