powershelldatetimepowershell-2.0datetime-format

Set up default date format like yyyy-mm-dd in Powershell?


A simple & short question:

How can I setup a default date format in powershell like yyyy-mm-dd ? so any date output will be like this format?

or How to setup a date format globally in one script ?

Is there a way to output date only without time? when I output LastWriteTime, Default is

13-03-2014 14:51

I only need 13-03-2014, without the 14:51 part.


Solution

  • A date in PowerShell is a DateTime object. If you want a date string in a particular format, you can use the built-in string formatting.

    PS C:\> $date = Get-Date
    PS C:\> $date.ToString("yyyy-MM-dd")
    2014-04-02
    

    You can also use the string format (-f) operator:

    PS C:\> "{0:yyyy-MM-dd}" -f $date
    2014-04-02
    

    The LastWriteTime property of a file is a DateTime object also, and you can use string formatting to output a string representation of the date any way you want.

    You want to do this:

    Get-ChildItem -Recurse \\path\ -filter *.pdf | Select-Object LastWriteTime,Directory
    

    You can use a calculated property:

    Get-ChildItem C:\Users\Administrator\Documents -filter *.pdf -Recurse |
      Select-Object Directory, Name, @{Name="LastWriteTime";
      Expression={$_.LastWriteTime.ToString("yyyy-MM-dd HH:mm")}}
    

    Run

    help Select-Object -Full
    

    and read about calculated properties for more information.