16

一个简单而简短的问题:

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

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

有没有办法只输出日期而没有时间?当我输出 LastWriteTime 时,默认为

13-03-2014 14:51

我只需要13-03-2014但是14:51

4

3 回答 3

19

PowerShell 中的日期是一个DateTime对象。如果你想要一个特定格式的日期字符串,你可以使用内置的字符串格式。

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

您还可以使用字符串格式 ( -f) 运算符:

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

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

你想这样做:

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

您可以使用计算属性:

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

help Select-Object -Full

并阅读计算属性以获取更多信息。

于 2014-04-03T01:35:57.467 回答
12

为了始终使用,您可以添加 .\Documents\WindowsPowerShell\profile.ps1

$culture = (Get-Culture).Clone()
$culture.DateTimeFormat.ShortDatePattern = 'yyyy-MM-dd'
Set-Culture $culture
于 2018-02-21T08:34:42.363 回答
11

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

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

如果您在为 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
于 2015-11-11T09:38:36.157 回答