在Powershell中设置默认日期格式,如yyyy-mm-dd?

Roo*_*oop 8 powershell powershell-2.0 powershell-3.0 powershell-4.0

一个简单而简短的问题:

如何在powershell中设置默认日期格式,如yyyy-mm-dd?所以任何日期输出都会像这种格式?

或如何在一个脚本中全局设置日期格式?

有没有办法只在没有时间的情况下输出日期?当我输出LastWriteTime时,默认为

13-03-2014 14:51

我只需要13-03-201414:51.

Bil*_*art 11

PowerShell中的日期是DateTime对象.如果您想要特定格式的日期字符串,只需使用内置字符串格式.

PS C:\> $date = get-date
PS C:\> $date.ToString("yyyy-MM-dd")
2014-04-02
Run Code Online (Sandbox Code Playgroud)

文件的LastWriteTime属性也是DateTime对象,您可以使用字符串格式以任何方式输出日期的字符串表示形式.

你想这样做:

gci -recu \\path\ -filter *.pdf | select LastWriteTime,Directory
Run Code Online (Sandbox Code Playgroud)

您可以使用计算属性:

get-childitem C:\Users\Administrator\Documents -filter *.pdf -recurse |
  select Directory, Name, @{Name="LastWriteTime";
  Expression={$_.LastWriteTime.ToString("yyyy-MM-dd HH:mm")}}
Run Code Online (Sandbox Code Playgroud)

help select-object -full
Run Code Online (Sandbox Code Playgroud)

并阅读有关计算属性的更多信息.


Alb*_*ban 11

对于始终使用,您可以添加到您的 .\Documents\WindowsPowerShell\profile.ps1

$culture = (Get-Culture).Clone()
$culture.DateTimeFormat.ShortDatePattern = 'yyyy-MM-dd'
Set-Culture $culture
Run Code Online (Sandbox Code Playgroud)


Mos*_*ini 10

我用过这个,它对我有用,只需在脚本的开头复制它

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

如果您在为 CultureInfo 加载程序集时发现问题(我在 Windows 2008 Server 上遇到了这个问题),请以这种方式更改第 2 行

$currentThread = [System.Threading.Thread]::CurrentThread
$culture = $CurrentThread.CurrentCulture.Clone()
$culture.DateTimeFormat.ShortDatePattern = 'dd-MM-yyyy'
$currentThread.CurrentCulture = $culture
$currentThread.CurrentUICulture = $culture
Run Code Online (Sandbox Code Playgroud)

  • 这比必须在每个输出行上使用 .ToString 更有用 (4认同)