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

天涯浪子 提交于 2019-11-30 03:44:58

问题


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 but 14:51.


回答1:


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

PS C:\> $date = get-date
PS C:\> $date.ToString("yyyy-MM-dd")
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:

gci -recu \\path\ -filter *.pdf | select LastWriteTime,Directory

You can use a calculated property:

get-childitem C:\Users\Administrator\Documents -filter *.pdf -recurse |
  select 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.




回答2:


i've 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 you'll 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



回答3:


for always usage you can add in your .\Documents\WindowsPowerShell\profile.ps1

$culture = Get-Culture
$culture.DateTimeFormat.ShortDatePattern = 'yyyy-MM-dd'
Set-Culture $culture


来源:https://stackoverflow.com/questions/22826185/setup-default-date-format-like-yyyy-mm-dd-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!