Setup default date format like yyyy-mm-dd in Powershell?

Setup default date format like yyyy-mm-dd in Powershell?

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:UsersAdministratorDocuments -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.

for always usage you can add in your .DocumentsWindowsPowerShellprofile.ps1

$culture = (Get-Culture).Clone()
$culture.DateTimeFormat.ShortDatePattern = yyyy-MM-dd
Set-Culture $culture

Setup default date format like yyyy-mm-dd in Powershell?

ive used this, it works for me, just copy it at the beginning of your script

$currentThread = [System.Threading.Thread]::CurrentThread
$culture = [CultureInfo]::InvariantCulture.Clone()
$culture.DateTimeFormat.ShortDatePattern = yyyy-MM-dd
$currentThread.CurrentCulture = $culture
$currentThread.CurrentUICulture = $culture

in case youll find problem in loading assembly for CultureInfo (i had this issue on Windows 2008 Server), change line 2 in this way

$currentThread = [System.Threading.Thread]::CurrentThread
$culture = $CurrentThread.CurrentCulture.Clone()
$culture.DateTimeFormat.ShortDatePattern = dd-MM-yyyy
$currentThread.CurrentCulture = $culture
$currentThread.CurrentUICulture = $culture

Related Posts

Leave a Reply

Your email address will not be published.